2

I have wrote a PHP script to handle user login. To prevent SQL Injection attack, I have used 'mysql_real_escape_string' function. Everything works good till today. I have traced code and finding the problem; the line using 'mysql_real_escape_string'. I have change it to basic command following:

$username=mysql_real_escape_string('sample');
var_dump($username)

The output is:

bool(false)

On my local web server (WAMP) everything is ok, but on remote host the problem appears! What is wrong? (Host PHP is 5.4.12)

SuB
  • 2,250
  • 3
  • 22
  • 37
  • 4
    Are you sure that the mysql connection is opened before you call `mysql_real_escape_string()`? – hek2mgl Nov 10 '13 at 11:02
  • Do note that `mysql_real_escape_string` is not the right way to [defend against SQL injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?lq=1). Not to mention it's deprecated... – DCoder Nov 10 '13 at 11:05
  • The `mysql_*` functions are **no longer maintained** and shouldn't be used in any new codebase. It is being phased out in favor of newer APIs. Instead you should use [**prepared statements**](https://www.youtube.com/watch?v=nLinqtCfhKY) with either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). – tereško Nov 10 '13 at 11:57

2 Answers2

10

According to http://php.net/manual/en/function.mysql-real-escape-string.php

Returns the escaped string, or FALSE on error.

It returns false on error;

Add the following line to the head of the file:

error_reporting(E_ALL);

so you can view the error.

It is possible that you forgot to make a mysql connection, before using the function mysql_real_escape_string('sample') Thats according to the first error in http://us1.php.net/mysql-real-escape-string

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

You should know that there are better ways to prevent sql injection which you can view here: How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Weiner Nir
  • 1,435
  • 1
  • 15
  • 19
3

Returns the escaped string, or FALSE on error.

Documentation

I can't tell you what the error is exactly, but it's almost certainly this:

Note:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592