I want to sum two columns' row and then the value insert the other column's row in the same table using php update. Is it possible?


I want to sum two columns' row and then the value insert the other column's row in the same table using php update. Is it possible?



I want to sum two columns' row and then the value insert the other column;s row in the same table using php update. Is it possible?



I try many time but the updated value in all row are same. Like:


id-1, total-150
id-2, total-150
id-3, total-150



Now what can I do?



MySQL table looks like this:
Mysql Table Look Like



My code:


<?php
$conn= new mysqli("localhost", "root", "", "zidm");

$sql = "SELECT * from exam_model ";
foreach ($conn->query($sql) as $row){
$total= $row['English'] + $row['Math'];

$sql="UPDATE exam_model SET total='$total' ";
mysqli_query($conn,$sql);
}
?>





Your update updates all rows , you just need one update like UPDATE exam_model SET total= 'Math' + 'English'
– FatFreddy
Jun 29 at 10:39





2 Answers
2



If you need an update on single row you should add a where clause eg:


<?php
$conn= new mysqli("localhost", "root", "", "zidm");


$sql = "SELECT * from exam_model ";
foreach ($conn->query($sql) as $row)
{
$total= $row['English'] + $row['Math'];
$id = $row['id'];

$sql="UPDATE exam_model SET total='$total' WHERE id = $id";
mysqli_query($conn,$sql);
}

?>



you missing WHERE clauses.


<?php
$conn= new mysqli("localhost", "root", "", "zidm");

$sql = "SELECT * from exam_model ";
foreach ($conn->query($sql) as $row){
$total= $row['English'] + $row['Math'];
$id = $row['id'];<br>
$sql="UPDATE exam_model SET total='$total' WHERE id = $id";
mysqli_query($conn,$sql);
}
?>





Please format the code in your answer.
– Script47
Jun 29 at 10:39





Thank You .You Both Are right.
– Shyful74
Jun 29 at 11:02






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV