簡體   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