0

example, I have a database and 1 table, inside the table is id, user, votes,

id = primary and auto increment

users = varchar

votes = int

how do I total the values inside the votes field and echo it?

3
  • Can you show a sample database record and your current code? Commented Oct 18, 2016 at 12:12
  • SELECT SUM(votes) as votes FROM table?? looking for ths? Commented Oct 18, 2016 at 12:13
  • check my post i type my database stracture there Commented Oct 18, 2016 at 12:16

2 Answers 2

5

Try this,

$result = mysql_query('SELECT SUM(votes) AS value_sum FROM table_name'); 
$row = mysql_fetch_assoc($result); 
$sum = $row['value_sum'];

With SQLi

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT SUM(votes) AS value_sum FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "sum is : " . $row["value_sum"];
    }
} else {
    echo "0 results";
}
$conn->close();
Sign up to request clarification or add additional context in comments.

5 Comments

Please don't advise mysql_* functions.
how to do this in mysqli?
holy molly! thanks for this answer @Dave it works like a charm. been looking for this for some time. hehe
@Dave yeah i already figured it out with the help from your previous comment
@ChumChum : you welcome, accept the Answer if it is useful to You.
1

1) Query:

SELECT SUM(votes) FROM `table`

2) Put the results in a variable and echo it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.