I am trying to add all the values in a single column from a table and then echo that value
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT sum(paid) as total_paid from users";
$result = $conn->query($sql);
echo $result;
But I end up getting this error:
Catchable fatal error: Object of class mysqli_result could not be converted to string in
Why and how can I fix?
This is too long for a "comment".
You need to loop over the results and use a while
loop, rather than echoing the query which is why you're getting the present error.
You also need to make sure that the paid
column's type can be used to perform mathematical problems, such as int
for instance (for example). If it's varchar
, then you will need to cast it to an integer.
References:
Here is a procedural style method:
$sql = "SELECT sum(paid) as total_paid from users";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
echo "Sum: " . $row['total_paid'];
}
or as an object-oriented method:
while($row = $result->fetch_array()) {
echo $sum = $row['total_paid'];
}
Sidenote:
To calculate a row based on a user/id, add a WHERE
clause in your query.
I.e.: WHERE id='x'
This because $result
returns an object, not a string. You have to loop through it and echo the results. And since it is only one row (because SUM
without a group by
always returns only one value, therefore only one row), you can do this:
if ($row = $result->fetch_assoc()) {
echo $row['total_paid'];
}
Or, use fetch_object()
directly:
echo $result->fetch_object()->total_paid;