繁体   English   中英

用计算出的变量更新多行

[英]update multiple rows with calculated variable

table_calc结构(最小化)为:

| id | value_1 | value_2 |

行数在70到250之间或更多。

我想用其他计算($ value_update_1和2,...)得出的值更新“ table_calc”中的字段,这些值应用于表中的字段。

在使用网页上的表格之前,我从那里更新了表格。 现在,我想直接更新值,而不必将其带入页面,因为它应该可以工作。

我开始编写以下代码:

$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach($result_stmt_update as $rrows_update) {
  $cal_id = $rrows_update[id];
  $cal_value_1 = $rrows_update['value_1'];
  $cal_value_2 = $rrows_update['value_2'];
}

$value_update_1 = 100.25;
$value_update_2 = 150.25;

$count_id = count($cal_id);
$stmt = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i = 0;
while($i < $count_id) {
  $stmt->bindParam(':value_1', '.$cal_value_1[$i].' * '.$value_update_2.');
  $stmt->bindParam(':value_2', '.$cal_value_2[$i].' * '.$value_update_1.');
  $stmt->bindParam(':id', $cal_id[$i]);
  $stmt->execute();
  $i++;
}

但这不起作用

你能帮我吗?

我可以在您的代码上发现一些问题:

  • 在第8行:

     $cal_id = $rrows_update[id]; ^^ 

    您需要在那里报价。

  • 在第20行,您将变量当作数组来调用,但在第9-10行中未将其设置为变量。
  • 还是在第20行,您应该将最终值绑定到参数,而不是让它由MySQL评估。

因此,更正的版本将是:

$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach ($result_stmt_update as $rrows_update) {
    //Added array push operators. To make them arrays.
    $cal_id[]      = $rrows_update["id"];
    $cal_value_1[] = $rrows_update['value_1'];
    $cal_value_2[] = $rrows_update['value_2'];
}

$value_update_1 = 100.25;
$value_update_2 = 150.25;

$count_id = count($cal_id);
$stmt     = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i        = 0;
while ($i < $count_id) {
    //Altered the binding so that you bind the final value.
    //Also changed to bindValue.
    $stmt->bindValue(':value_1', $cal_value_1[$i] * $value_update_2);
    $stmt->bindValue(':value_2', $cal_value_2[$i] * $value_update_1);
    $stmt->bindValue(':id', $cal_id[$i]);
    $stmt->execute();
    $i++;
}

另外,在对数据库进行批量更改时,您可能需要使用Transactions ,以确保所有更改均按预期注册。

暂无
暂无

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

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