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));
   }
Kayden
  • 133
  • 3
  • 16
  • [Escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe. [Check this out.](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 09 '17 at 15:55
  • @JayBlanchard Can now add multiple dupe reasons. I added that Q as a second dupe – Machavity Mar 09 '17 at 16:03
  • Awesome @Machavity. I didn't know that. – Jay Blanchard Mar 09 '17 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? – Kayden Mar 09 '17 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](https://phpdelusions.net/programming#reporting_errors). – Your Common Sense Mar 09 '17 at 16:37

0 Answers0