I am trying to run the following script within my PHP script to calculate a running total.
<?php // Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "set @csum := 0; select date(`DATE`) as dadate, Price , (@csum := @csum + Price) as cumulative_sum from Profits WHERE Strat = 'arm' order by dadate;";
$result = $conn->query($sql)or die($conn->error);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "{time: '" . $row["Date"]. "', value: ".$row["cumulative_sum"]. "},<br>";
}
} else {
echo "0 results";
}
$conn->close(); ?>
I believe I am getting the error below because I am running 2 queries at once but am only supposed to execute one query at a time.
check the manual that corresponds to your MySQL server version for the
right syntax to use near ‘select date(daDATE
), Price ,
(@csum := @csum + Price) as cumulative_’ at line 1
Is there any way around this is a need to set :csum to 0 to ensure it starts from 0
2
Answers
Strictly speaking, this is incorrect, but I cannot find an example of it not working (in MySQL versions prior to 8.0)…
Note that because you’re passing the result to application code, you could just ad easily handle the cumulative arithmetic there
Another initialization variant (without SELECT, primarily useful for UPDATE if you need it to be single-table):