The table_calc structure (minimized) is:
| id | value_1 | value_2 |
the number of rows is between 70 and 250 or more.
I want to update the fields in "table_calc" with values resulting from other calculations ($value_update_1 and 2, ...), values applied different to the fields in the table.
Before I used a table on the web page and from there I updated the table. Now I want to update the values directly without having to take them in the page, as it should work.
I started to write the code below:
$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++;
}
but it doesn't work
Can you help?
I can spot a few issues on your code:
On line 8:
$cal_id = $rrows_update[id]; ^^
You need quotes there.
So the corrected version would be:
$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++;
}
Also, when making batch changes to the database, you may want to use Transactions , to make sure all changes are registered as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.