我试图产生一些异常来测试函数,所以我没有将任何数组传递给 $stmt->execute()
故意,我希望得到一个异常(exception),或者什么都没有(因为没有匹配的结果),但我仍然能够获取一些东西并打印出来???
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql='Select id from books where bookname=?';
$stmt=$conn->prepare($sql);
$stmt->execute();
if($row=$stmt->fetch(PDO::FETCH_ASSOC)){
print_array($row); //print_array is a function can print out key and the value
}
打印出来
[id] => 123 (just an example)
如果我将查询更改为
'Select * from books where bookname= ?';
它打印出表中的第一行数据。
我想知道在 execute() 和 fetch() 之间发生了什么....我直接在 phpmyadmin 中尝试了这些查询(我可以想象当它们到达数据库时查询会是什么样子),但没有得到相同的结果。
Select id from books where bookname= ?
Select id from books where bookname= '?'
Select id from books where bookname= ''
Select id from books where bookname= ' '
到目前为止,PDO 对我来说充满了惊喜......
顺便说一句,我什至 var_dump($stmt->execute())
并且它返回 true
。
更新:
我打开了
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
并尝试打印出 $conn->errorInfo()
和$stmt->errorInfo()
没有错误信息。还是刚得到结果。
但是,当我设置 $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
我得到了 PDOException:
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in ...
如果我关闭它,不管有没有 execute() 中的数组,它都可以正常工作。
但很多文章都希望这个属性为假,以防止 SQL 注入(inject)。
在我的例子中,将它设置为 false 似乎只是为了允许以某种方式注入(inject)。
有什么想法吗?
最佳答案
你已经执行了你认为的其他语句
$conn->prepare($sql); // there is no assign
$stmt->execute();
改成
$stmt = $conn->prepare($sql); // there is assign
$stmt->execute();
关于php - PDO 即使没有绑定(bind)任何参数仍然会得到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25206117/