根据PHP手册,您可以通过询问$stmt->错误和$stmt-> errno来检索任何预准备语句方法中的错误但是bind_param方法似乎永远不会设置这些错误,其他人可以确认吗?或者告诉我,我错过了什么?
例如:
echo "Start\n";
$db = new MysqLi('localhost','test','xxxxxx','test');
$val = 1;
$st = $db->prepare('insert into tblTest set field1=?');
if($st == false)
{
printf("prepare: %s %d\n",$db->error,$st->errno);
}
$rs = $st->bind_param('is', $val);
if($rs == false)
{
printf("bind_param: %s %d\n",$st->error,$st->errno);
}
$rs = $st->execute();
if($rs == false)
{
printf("execute: %s %d\n",$st->error,$st->errno);
}
$rs = $st->close();
if($rs == false)
{
printf("close: %s %d\n",$st->error,$st->errno);
}
echo "Finish\n";
Start
PHP Warning: MysqLi_stmt::bind_param(): Number of elements in type deFinition string doesn't match number of bind variables in test.PHP on line 14
bind_param: 0
execute: No data supplied for parameters in prepared statement 2031
Finish
因此,PHP将此视为警告,bind_param返回false,但错误& errno没有设置.执行也失败并正确设置错误&错误号
解决方法:
MysqLi :: error和MysqLi :: errno是RDBMS返回给PHP的错误代码和消息的容器,而不是设置语句时PHP代码中遇到的错误.对bind_param()的错误调用(参数不足)显然不会与RDBMS通信,因此不会从RDBMS接收错误.
根据to the docs,bind_param()在失败时返回一个布尔值FALSE.因此,您需要验证它是否已成功调用.
$rs = $st->bind_param('is', $val);
if ($rs) {
$st->execute();
}