Php mysqli绑定参数
让我们假设我们有一个包含字段“id”和“num”的表“item”,还有下面这样一个不起作用的代码Php mysqli绑定参数,php,mysqli,Php,Mysqli,让我们假设我们有一个包含字段“id”和“num”的表“item”,还有下面这样一个不起作用的代码 $db = new mysqli('localhost', 'user', 'pass', 'db') ; if (!$st = $db->prepare('select id from item')) die($db->error) ; if (!$st2 = $db->prepare('update item set num = 1 where id = ?')) die
$db = new mysqli('localhost', 'user', 'pass', 'db') ;
if (!$st = $db->prepare('select id from item')) die($db->error) ;
if (!$st2 = $db->prepare('update item set num = 1 where id = ?')) die($db->error) ;
$st->execute() ;
$st->bind_result($id) ;
while ($st->fetch()) {
$st2->bind_param('i', $id) ;
$st2->execute() ;
echo $id.'<br/>' ;
}
$db=newmysqli('localhost','user','pass','db');
如果(!$st=$db->prepare('select id from item'))死亡($db->error);
如果(!$st2=$db->prepare('updateitemsetnum=1,其中id=?'))死亡($db->error);
$st->execute();
$st->bind_结果($id);
而($st->fetch()){
$st2->bind_参数('i',$id);
$st2->execute();
回显$id.“
”;
}
它只是打印出像这样的东西^
1.
2.
3.
但是没有任何更改会将plase id带到数据库中($st2->受影响的行等于零)。
怎么了
注意:不是真正的代码,但它完全描述了问题。根据文档,在执行之前必须调用绑定结果:
$st->bind_result($id) ;
$st->execute() ;
while ($st->fetch()) {
$st2->bind_param('i', $id) ;
$st2->execute() ;
echo $id.'<br/>' ;
}
$st->bind_结果($id);
$st->execute();
而($st->fetch()){
$st2->bind_参数('i',$id);
$st2->execute();
回显$id.“
”;
}
怎么了
由于某些原因,您不会对execute执行错误检查
$st2->execute() or trigger_error($db->error);
将告诉您查询是否有错误。如果没有-检查检查更新值的方式 顺便说一下,您的代码的更好版本
$dsn = 'mysql:host=localhost;dbname=db;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'user','pass', $opt);
$sth = $db->prepare('select id from item');
$sth->execute();
$ids = $sth->fetchAll();
$sth = $db->prepare('update item set num = 1 where id = ?');
foreach ($ids as $row) {
$sth->execute($row['id']);
}
发布非真实代码并询问它有什么问题是互斥的。没有任何变化,代码仍然打印出绑定的id,但更新查询不起作用。