-1

I'm trying to sanitize a variable and am having an issue.

This code outputs the echo correctly:

$to_raw = $_POST['to'] ;
echo $to_raw;

But this returns nothing:

$to_raw = mysql_real_escape_string($_POST['to']) ;
echo $to_raw;

Am I missing something?

Milksnake12
  • 551
  • 1
  • 9
  • 19
  • 6
    `mysql_real_escape_string` only works if you're connected to a database (it should throw a warning if you're not). Did you call `mysql_connect`? – gen_Eric Dec 20 '12 at 23:50
  • Aw, so this line needs to go below the mysql_connect? I have a connection, but it's lower in the code. – Milksnake12 Dec 20 '12 at 23:53
  • Yeah, you need to connect to the database before calling any other `mysql_` functions. – gen_Eric Dec 20 '12 at 23:53
  • 1
    Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/KJveJ). See the *[red box](http://goo.gl/GPmFd)*? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/3gqF9) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/vFWnC). – John V. Dec 20 '12 at 23:54

1 Answers1

2

The function mysql_real_escape_string doesn't work if you haven't called mysql_connect. Better workaround would be creating a MySQL connection on the top, before calling the mysql_real_escape_string.

mysql_connect("localhost");
$to_raw = mysql_real_escape_string($_POST['to']) ;
echo $to_raw;

Suggestion

It is better to use either PDO or mysqli_* functions compared to mysql_* functions as they are deprecated.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252