5

i have read countless articles but was wondering if someone could explain the difference to me in laymans terms? i know they both protect against sql injection and are for security. but if im using mysqli to run a query , or the old fashioned way of my_sql_query, does it really matter which one i use? are not they both wrappers anyway for the sql function?

why does the below code not work?

 $test="hello, 'there";
$db->real_escape_string($test);

$db->query("INSERT INTO users (first_name) VALUES ('$test')");
user3337617
  • 61
  • 1
  • 1
  • 3

2 Answers2

4

They take into account the current charset of the connection, so they need to be able to access the connection, so you have to use the one for the library you opened the connection with.

They should generally be avoided in favour of prepared statements though.

why does the below code not work?

$test="hello, 'there";
$db->query("INSERT INTO users (first_name) VALUES ('$test')", 

mysqli_real_escape_string($test));

You may have other issues but:

  1. You escape $test after you've injected it into the SQL
  2. You don't do anything with the return value.

This should go before you construct your string of SQL:

$test = mysqli_real_escape_string($link, $test);
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

In addition to what Quentin said:

Both kind of same output.

mysql_real_escape_string

$link is must for mysqli_real_escape_string.

mysql_real_escape_string

$link is optional

If the link identifier is not specified, the last link opened by mysql_connect() is used. If not then try to open one with no parameters.

Andolasoft Inc
  • 1,296
  • 1
  • 7
  • 16