Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between mysqli_real_escape_string() and mysql_real_escape_string()

Tags:

sql

php

mysqli

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')");
like image 732
user3337617 Avatar asked Oct 02 '22 13:10

user3337617


1 Answers

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);
like image 178
Quentin Avatar answered Oct 11 '22 04:10

Quentin