MySQLi& mysql_real_escape_string()错误

时间:2011-02-22 16:32:21

标签: php mysql mysqli

我正在使用OOP MySQLi连接到我的数据库。我检查了我的证书,一切都很好。

    $mysqli = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB) or die('There was a problem connecting to the database.');

    if (mysqli_connect_errno()) { 
       printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()); 
       exit; 
    }

    if ($result = $mysqli->query('SELECT * FROM places WHERE place_id=' . mysql_real_escape_string($_GET['id']))) { 
        while( $row = $result->fetch_assoc() ){ 
            printf("%s (%s)\n", $row['name'], $row['place_id']); 
        } 
        $result->close(); 
    } 

    $mysqli->close();

此代码生成错误:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access
denied for user '-removed-'@'localhost' (using password: NO) in
/var/www/vhosts/communr.com/httpdocs/pbd/places.php on line 396

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to
the server could not be established in
/var/www/vhosts/communr.com/httpdocs/pbd/places.php on line 396

我无法弄清楚为什么我会收到这些错误。最近我搬家时,他们开始展示。我在查询之前建立SQL连接。

你们都认为某些设置可能会在我的新服务器上搞砸了吗?

谢谢!

1 个答案:

答案 0 :(得分:15)

mysql_real_escape_string要求通过mysql_connect建立连接才能运作。 $mysqli->real_escape_string需要mysqli个对象才能运行。所以,

改为使用MySQli::real_escape_string

'SELECT * FROM places WHERE place_id='.$mysqli->real_escape_string($_GET['id']); 

但请注意,为了安全起见,您需要引用它:

'SELECT * FROM places WHERE place_id=\''.$mysqli->real_escape_string($_GET['id']).'\''; 

但是,因为它看起来像一个整数,所以你应该这样做而不是转义它:

'SELECT * FROM places WHERE place_id='.(int) $_GET['id'];