Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mysql - Sum of column in using mysqli and php

I am tring to get the sum of a column and the show it on my page using this code but it keeps returning a "1" when it should return "23" for example. I check my sql statement and it works fine. This is the code I am using. (note: My server is iis with php)

<?php
require('connection.php');

$sql="SELECT sum(amount) as total FROM td";

$result = mysqli_query($sql);

while ($row = mysqli_fetch_assoc($result)){ echo $row['total'];}

mysqli_close($con);
?>

ok so I added the while thing and it just breaks my code I get a white page.

I now removed the ! in the mysqli_query and I still get a white page, not sure if its me or the server that is not playing nice.

This may be unrelated but when I removed the ! from the mysqli_query from my other code it broke it.

<?php
require 'connection.php';
$date = $_POST['date'];
$comment = $_POST['comment'];
$amount = $_POST['amount'];

$sql= "INSERT INTO td (date, comment, amount) VALUES ('$date', '$comment', '$amount')";

if (mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

Everything is fixed Thanks Everyone!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

<?php
require('connection.php');

$sql="SELECT sum(amount) as total FROM td";

$result = mysqli_query($sql);

while ($row = mysqli_fetch_assoc($result))
{ 
   echo $row['total'];
}

mysqli_close($con);
?>

As said in a comment above, you don't need the ! infront of the query method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...