0

I have the following php script to insert a form user input data into the database. Is mysqli_real_escape_string enough to prevent SQL injection if I don't wish to use prepared statements to bind parameters to "?" placeholder?

   <?php
   $link = mysqli_connect("localhost", "root", "", "bizcontact");

   $name = mysqli_real_escape_string($link, $_POST['name']);
   $company = mysqli_real_escape_string($link, $_POST['company']);
   $position = mysqli_real_escape_string($link, $_POST['position']);
   $contact = mysqli_real_escape_string($link, $_POST['contact']);
   $email = mysqli_real_escape_string($link, $_POST['email']);
   $gender = mysqli_real_escape_string($link, $_POST['gender']);

   /* check connection */
   if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
   }

   $sql = "INSERT INTO businesscontact(name, company, position, phone,  email, gender) VALUES('$name', '$company', '$position', '$contact', '$email',  '$gender')";
   if (mysqli_query($link, $sql)){
   echo "success";
   }else{
   echo(mysqli_error($link));
   };

   /* close connection */
   mysqli_close($link);
   ?>

UPDATE

    $stmt = $link->prepare("INSERT INTO businesscontact(name, company, position, phone, email, gender) VALUES(?,?,?,?,?,?)");
    $stmt-> bind_param("ssssss", $name, $company, $position, $contact,  $email, $gender);
    if($stmt->execute()){
    echo "success";
   }else{
    echo(mysqli_error($link));
   }
5
  • Escaping the string is not safe. Check this out. Commented Mar 9, 2017 at 15:55
  • @JayBlanchard Can now add multiple dupe reasons. I added that Q as a second dupe Commented Mar 9, 2017 at 16:03
  • Awesome @Machavity. I didn't know that. Commented Mar 9, 2017 at 16:06
  • @JayBlanchard Would the prepared statement that I've updated above be better? Or how can I improve it to make it more secure? Commented Mar 9, 2017 at 16:33
  • It' is OK regarding the query itself but you can improve the security by preventing an error text to be leaked to a hacker. Commented Mar 9, 2017 at 16:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.