Skip to content
Home » Web » PHP » How to Resolve Warning: mysql_real_escape_string(): Access denied

How to Resolve Warning: mysql_real_escape_string(): Access denied

mysql_real_escape_string

When you deploy PHP programs to a higher version of PHP engine, you might see errors at run-time like this:

Warning: mysql_real_escape_string(): Access denied for user 'root'@'localhost' (using password: NO) in /var/www/html/index.php on line 57
Warning: mysql_real_escape_string(): A link to the server could not be established in /var/www/html/index.php on line 57

Actually, mysql_real_escape_string() not a pure PHP function, it calls back to MySQL's Library. Therefore, you need a underlying connection to MySQL before calling this function. The PHP manual shows a good example on this:

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password));
?>

Please refer to the official document for more information: PHP: mysql_real_escape_string - Manual. In which, a warning about this function is also in the document:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

Therefore, you should try not to use this function in the programs, because PDO provides the functionality of parameter-bindings which is able to escape special characters automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *