4

In old mysql() code, to escape a string, I did this:

t.TeacherUsername = '".mysql_real_escape_string($teacherusername)."'

I am changing my code to mysqli, but what I want to know for sure and to be safe, to escape a string in mysqli is it like this below:

t.TeacherUsername = '".mysqli_real_escape_string($teacherusername)."'

Also to connect to mysqli database is it like this below:

$username="xxx";
$password="xxx";
$database="xxx";

mysqli_connect('localhost',$username,$password);

mysqli_select_db($database) or die( "Unable to select database");

All I have done is change mysql to mysqli, is that correct?

UPDATE:

Is this now the correct way to connect to database using mysqli:

$username="xxx";
$password="xxx";
$database="mobile_app";

$mysqli = new mysqli("localhost", $username, $password, $database);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
user1394925
  • 754
  • 9
  • 28
  • 51
  • possible duplicate of [Is using mysqli_real_escape_string enough to secure my query string?](http://stackoverflow.com/questions/5200051/is-using-mysqli-real-escape-string-enough-to-secure-my-query-string) – JJJ Jun 06 '12 at 14:39

1 Answers1

4

Your use of the function is incorrect.

You MUST use the mysqli link resource returned by mysqli_connect as the first parameter to mysqli_real_escape_string.

Example:

$username="xxx";
$password="xxx";
$database="xxx";

$my = mysqli_connect('localhost',$username,$password);

mysqli_select_db($my, $database) or die( "Unable to select database");

$t->TeacherUsername = "'" . mysqli_real_escape_string($my, $teacherusername). "'";
SirDarius
  • 41,440
  • 8
  • 86
  • 100