我有一个以财务名称命名的MySQL表,它具有ID,余额,要求,ytotal6和预算列。
我想对余额列的值求和,并将结果写到id为1列的ytotal6中。

这是表结构link

这是我的index.php文件

$con=mysqli_connect("127.0.0.1","root","","dji001");
                $result = mysqli_query($con,"SELECT * FROM finance")
                or die("Error: ".mysqli_error($con));

                echo "<form style='width:1080px; backgrond-color:transparent;' action='update.php' method='post' class='form-group'>";
                    while($row = mysqli_fetch_array($result))
                    {
                    $id = $row['ID'];
                    $Budget = $row['Budget'];
                    $Balance = $row['Balance'];
                    $Requested = $row['Requested'];
                    $balance = $Requested + $Budget;

                    $con->query("UPDATE finance SET balance = $balance WHERE id = $id");
                    echo "<div class='calc_container'>

                    <input type='hidden' class='id' name='id[]' value='".$row['ID']."'>

                    <input type='text' class='budget' name='Budget[]' value='".$row['Budget']."'>

                    <input type='text' class='req_kbl' name='Requested[]' value='".$row['Requested']."'>

                    <input type='text' class='balance' name='Balance[]' value='".$row['Balance']."'>

                    </div>";}

                            $result = mysqli_query($con,"SELECT * FROM finance where id=1")
                            or die("Error: ".mysqli_error($con));
                            while($row = mysqli_fetch_array($result))
                            echo"
                            <input type='text' class='ytotal6' name='ytotal6' value='".$row['ytotal6'] ."'>";
                            echo "<input type='Submit' class='button' value='Submit'></form>";


我已经尝试过$ytotal6 = sum[$balance];,但是没有用。

最佳答案

对于“对余额列值求和并将结果写到id为1列的ytotal6中”,请尝试以下操作

  UPDATE finance f1, (SELECT SUM(balance) AS bal
            FROM finance ) f2
  SET ytotal6 = bal
  WHERE f1.id = 1;


注意:对于诸如“您无法在FROM子句中指定目标表进行更新”之类的错误,我们需要创建一个临时表

关于php - 对特定的MySQL表列求和,并将结果写入其他列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29470560/

10-09 07:35