MySQLi& mysql_real_escape_string()错误 [英] MySQLi & mysql_real_escape_string() Errors
问题描述
我正在使用OOP MySQLi连接到我的数据库.我已经检查了我的凭据,一切顺利.
I am using OOP MySQLi to connect to my database. I have checked my credentials and everything is good to go.
$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连接.
I can't figure out why I am getting these errors. They started showing when I moved servers recently. I am establishing an SQL connection before the query.
你们都认为我的新服务器上的某些设置可能会混乱吗?
Do you all think some setting could be messed up on my new server?
谢谢!
推荐答案
mysql_real_escape_string
需要通过mysql_connect
建立的连接才能正常工作. $mysqli->real_escape_string
需要一个mysqli
对象才能工作.所以,
mysql_real_escape_string
requires a connection to be established via mysql_connect
in order to work. $mysqli->real_escape_string
requires a mysqli
object to work. So,
使用 MySQli::real_escape_string
代替:>
'SELECT * FROM places WHERE place_id='.$mysqli->real_escape_string($_GET['id']);
但是请注意,为了安全起见,您需要引用它:
But note that you'd need to quote it in order to be safe:
'SELECT * FROM places WHERE place_id=\''.$mysqli->real_escape_string($_GET['id']).'\'';
但是,由于它看起来像一个整数,因此应将其强制转换,而不是转义:
However, since it looks like an integer, you should cast it as such instead of escaping it:
'SELECT * FROM places WHERE place_id='.(int) $_GET['id'];
这篇关于MySQLi& mysql_real_escape_string()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!