我想对两列求和';行,然后将值插入另一列';在同一个表中使用php更新。可能吗?

我想对两列求和';行,然后将值插入另一列';在同一个表中使用php更新。可能吗?,php,mysql,Php,Mysql,我想对两列的行求和,然后将值插入另一列;在同一个表中使用php更新。可能吗 我尝试了很多次,但所有行中的更新值都相同。比如: id-1, total-150 id-2, total-150 id-3, total-150 现在我能做什么 MySQL表如下所示: 我的代码: <?php $conn= new mysqli("localhost", "root", "", "zidm"); $sql = "SELECT * from exam_

我想对两列的行求和,然后将值插入另一列;在同一个表中使用php更新。可能吗

我尝试了很多次,但所有行中的更新值都相同。比如:

id-1, total-150
id-2, total-150
id-3, total-150
现在我能做什么

MySQL表如下所示:

我的代码

<?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);
}
?>

您缺少WHERE子句。

<?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); 
}
?>

如果需要对单行进行更新,则应添加where子句,例如:

<?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);
    }

?>

您的更新更新了所有行,您只需要一个更新,如更新考试\模型集总计='Math'+'English'