我的pdo连接不起作用
回想我之前关于SQL注入的问题.我正在尝试建立PDO连接.
Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
为此,我想用新代码替换旧代码:
For that I want to replace my old code with the new:
这是旧的
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
这是新的:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
当我尝试这个新代码时.它给出以下错误:
When I tried this new code.. It gives the following error:
错误!:SQLSTATE [HY000] [1045]用户访问被拒绝 'sec'@'localhost'(使用密码:是)
Error!: SQLSTATE[HY000] [1045] Access denied for user 'sec'@'localhost' (using password: YES)
我还尝试用127.0.0.1替换localhost.
I also tried to replace localhost with 127.0.0.1.
我的目标是使我的页面安全进行SQL注入.
My goal is to make my page secure for SQL-injection.
任何人都可以找到很好的解决方案!
May anyone have a great solution!
乍一看,代码看起来还不错. 尝试此解决方案.看来这个匿名用户可能是问题所在.
The code looks ok at first glance. Try this solution. It looks like this anonymus user might be the problem.
(根据评论的建议)
总结: 推荐的解决方案是删除该匿名用户.通过执行
In summary: The recommended solution is to drop this anonymous user. By executing
DROP USER ''@'localhost';