Question

OK guys, I'm having trouble with mysql_real_escape_string. It is a simple POST table with title and contents, which should in theory work fine (by me).

$db = new mysqli('...','...','...','...') or die ('error with connection');
$db->set_charset('utf8');

$title  = trim($_POST['title']);
$contents   = trim($_POST['contents']);

$title = mysql_real_escape_string($title);
$contents = mysql_real_escape_string($contents);

$sql = "INSERT INTO posts SET title = '$title', contents = '$contents'";
$query = $db->query($sql);

I found when I place 'echo' before and after 'mysql_escape_string' like:

echo 'before' . $title;
$title = mysql_real_escape_string($title);
echo 'after' . $title;

that it echoes the title on the "before" line, but on the "after" line it echoes blank $title.

Note: whan I use 'mysql_escape_string' instead (of real), it works fine (but I guess this is weaker protection).

Any ideas?? Thank you.

Was it helpful?

Solution

The reason title is empty is because mysql_real_escape_string is returning FALSE. This happened because it requires a MySQL connection to the database, you have MySQLi. From the docs,

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned

The way to fix the issue is to use mysqli_real_escape_string to match your database connection, as suggested in the other answers. Obviously for security, you're better off using prepared statements.

Also, the database link needs to be supplied. Since you're using the OO style, this is done as

$db = new mysqli()
$title = $db->real_escape_string($title)

OTHER TIPS

mysql_real_escape_string() works in context of connection made by "mysql" extension, but you use "mysqli".

You need to either connect using mysql_connect() not recommended

Or you need to use new approaches from mysqli such as prepared statements or mysqli_real_escape_string()

You should not interpolate user-generated strings into sql. Use prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

In your case:

$db = new mysqli('...','...','...','...') or die ('error with connection');
$db->set_charset('utf8');

$title  = trim($_POST['title']);
$contents   = trim($_POST['contents']);

$sql = $db->prepare("INSERT INTO posts (title, contents) VALUES (?,?)");
$sql->bind_param('ss', $title, $contents);
$sql->execute();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top