PHP mysql_real_escape_string returns empty string

Drake picture Drake · Apr 26, 2012 · Viewed 27.4k times · Source

I'm trying to work a bit of security and sanitization into my databases application (for a class). to start off with, i'm trying to use mysql_real_escape_string, but whenever i use it, it always returns an empty string!

Here's the connection code:

include_once ("./connect.php");
$db_connection = new mysqli($SERVER, $USERNAME, $PASSWORD, $DATABASE);
if (mysqli_connect_errno()) {
    echo("Can't connect to MySQL Server. Error code: " . mysqli_connect_error());
    return null;
}
$field = mysql_real_escape_string($_GET['value']);
$upc = $_GET['upc'];
$type = $_GET['field_type'];
echo $field;
echo $upc;
echo $type;

When the php actually gets executed, the $upc and $type gets printed, but NOTHING for $field. Ive tried using an intermediate string, but i get the same result. I'm seriously at a loss as to what it is thats going wrong here.

Also, I've done a var_dump on $field, and it claims mysql_real_escape_string returns FALSE, which is supposed to happen when there isn't a connection(?), but there is one.

Answer

jeroen picture jeroen · Apr 26, 2012

You are connecting using mysqli, not mysql, so you need mysqli_real_escape_string

Although you could easily use prepared statements in mysqli and then you wouldn't need either...