I have a MySQL table by the name of finance and it have id, balance, requested, ytotal6 and budget column. I want to sum the balance column values and write the result in ytotal6 where id is 1 column.
This is the table structure link
This is my index.php file
$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>";
I have tried $ytotal6 = sum[$balance];
but it didn't work.
For "sum the balance column values and write the result in ytotal6 where id is 1 column" try this
UPDATE finance f1, (SELECT SUM(balance) AS bal
FROM finance ) f2
SET ytotal6 = bal
WHERE f1.id = 1;
Note: For error like "You can't specify target table for update in FROM clause" we need to create a temporary table
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.