-1

Hi im currently learning php and mysql a tutorial i am following uses the now out of date mysql_real_escape_string ive read the manual on mysqli's version of it but just cant really figure out how i would do something like the code below.

$username = mysql_real_escape_string($POST['username']);

any help in converting this over to mysqli and any tips are greatly apreciated

GregHBushnell
  • 143
  • 12
  • You'd use prepared statements which escape for you or: http://php.net/manual/en/mysqli.real-escape-string.php – noahnu Aug 30 '16 at 17:57
  • Have a look at the manual http://php.net/manual/en/mysqli.real-escape-string.php – jmattheis Aug 30 '16 at 17:58
  • It's basically the same except that you pass the connection object as the first argument. – Barmar Aug 30 '16 at 17:59
  • [This Q&A is well worth a read](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string). Use prepared statements. – Martin Aug 30 '16 at 18:03
  • http://stackoverflow.com/documentation/php/275/using-a-database/2685/preventing-sql-injection-with-parametrized-queries – Machavity Aug 30 '16 at 18:13
  • sorry for the duplicate i did try searching but i guess i was being too specific – GregHBushnell Aug 30 '16 at 18:49

3 Answers3

1
$username = $mysqli->real_escape_string($POST['username']);
  • 1
    It's worth noting that the above notation is the Object Orientated notation. (This will confuse anyone trying to code SQL connections procedurally.) – Martin Aug 30 '16 at 18:04
  • hi thanks for your answer but i had already tried that unfortunatly i keep getting Undefined variable error – GregHBushnell Aug 30 '16 at 18:35
0

I think you want this

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$username = mysqli_real_escape_string($con, $_POST['username']);
mysqli_close($con);
?>
Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43
0

First, create your connection and store it in a variable $link.

$link = mysqli_connect("localhost", "root", "", "my_table");

Use this $link as the first parameter in mysqli_real_escape_string.

$username= mysqli_real_escape_string($link, $POST['username']);

Reference: Example of mysqli_real_escape_string

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32