简体   繁体   English

mysqli bind_param

[英]mysqli bind_param

lets pretend we have a table 'item' with fields 'id' and 'num' and also a code like below that doesn't work. 假设我们有一个表“ item”,其中包含字段“ id”和“ num”,并且下面的代码不起作用。

$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/>' ;
}

It just print out something like^ 1 2 3 but no changes takes plase id the database ($st2->affected_rows equals zero). 它只打印出类似^ 1 2 3的内容,但没有任何变化,请输入数据库的ID($ st2-> affected_rows等于零)。 What's wrong with it? 它出什么问题了?

PS Not the real code, but it totally describes the problem. PS不是真正的代码,但它完全描述了问题。

What's wrong with it? 它出什么问题了?

For some reason you do no error checking for execute. 由于某些原因,您不执行错误检查。

$st2->execute() or trigger_error($db->error);

will tell you if there was an error with query. 会告诉您查询是否有错误。
if there was none - check the way you're checking your updated values. 如果没有,请检查您检查更新值的方式。

by the way, better version of your code 顺便说一句,更好的代码版本

$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']);
}

According to the documentation bind_result has to be called before execute : 根据文档,必须在执行之前调用bind_result:

$st->bind_result($id) ;
$st->execute() ;
while ($st->fetch()) {

    $st2->bind_param('i', $id) ;
    $st2->execute() ;
    echo $id.'<br/>' ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM