I am trying to add the result of 3 SQL queries. All 3 queries return integer values.
How can I add the results from the 3 SQL queries into a variable and echo it? The code:
<?php
define('HOST','mywebsite.com');
define('USER','username');
define('PASS','password');
define('DB','imagebase');
$con=mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='POST'){
$val1=$_POST['sval1'];
$val2=$_POST['sval2'];
$val3=$_POST['sval3'];
$sql="select price from images where name='$val1'"; //returns 100
$sql1="select price from images where name='$val2'"; //returns 100
$sql2="select price from images where name='$val3'"; //returns 100
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
$result1=mysqli_query($con,$sql1);
$count1=mysqli_num_rows($result1);
$result2=mysqli_query($con,$sql2);
$count2=mysqli_num_rows($result2);
if ($count==1) {
$res1=$count;
}
if ($count1==1) {
$res2=$count;
}
if ($count2==1) {
$res3=$count;
}
$final=$res1+$res2+$res3; //should return 300 but returns 3
echo $final;
mysqli_close($con);
} else {
echo 'Error Updating Price';
mysqli_close($con);
}
?>
$final=$res1+$res2+$res3; echo $final;SELECT SUM(price) FROM images WHERE name IN (?, ?, ?). Also, you're open to SQL injection attacks. Read about PDO - phpdelusions.net/pdomysqli_num_rowsreturns the number of rows in the query result, not the actual result. So each time you call it, it returns 1. You need to fetch the results from the queries before trying to add them. Or, you could get all three in one query as the other comment suggests. Either way, you'll have to fetch.mysqli_num_rowswill not do it.