mysql_real_escape_string not showing error

2019-09-05 16:01发布

问题:

I am moving my application from Mysql extension to PHP PDO. I am facing a strange problem. In my development environment, I have both db server [MySQL] and web server are in single system where as in testing environment web and db servers are in different system.

The following test code runs perfectly in dev environment and fails in test environment.

    require "class.DB.php" ;

    class DbMaster extends DB
    {
        public function __construct()
        {
            $this->Host     = "192.168.1.00";
            $this->Database = 'test_database';
            $this->User     = "root";
            $this->Password = "12345";
        }
    }

    // Creates the instance
    $db = new DbMaster();

    $table = mysql_real_escape_string('persons');
    $result_array = $db->query("SELECT Id, Age FROM $table WHERE Id >= :Id", array("Id" => 1));

    foreach ($result_array as $rec)
    {
        echo '<br>'.$rec["Id"].' -> '.$rec['Age'];

    }

In dev, mysql_real_escape_string should fail, because there is no mysql_connect().

But, mysql_real_escape_string works when there is a mysql server running locally. To test this in dev environment I stopped the local mysql and connected to remote database. Then I got the following error:

Warning: mysql_real_escape_string(): A link to the server could not be established 

So with my existing development setup [both web and db server together], I am not able to see the PDO related errors.

Any way to resolve this problem.

回答1:

mysql_real_escape_string() tries to open a connection to a server with mysql_connect() if no connection exist. The default values for mysql_connect() are "localhost" and "root" without a password.

If you have the root account without a password in your development environment (which is a pretty common setup) this will work without problem, since a connection can be esteblished.

On the live environment on the other hand, the root user hopefully has a password set, so this call will fail.

In this case mysql_real_escape_string() will return false instead of your escaped value.

The solution: Use the mysqli or PDO equivalent of the function. Or open an additional connection using mysql_connect() with valid credentials for the time being so mysql_real_escape_string() can use it.