3

I have a MySQL database and in one column, I have numbers (price) and I need to count all numbers in this column with PHP... How can I do that?

5 Answers 5

14

If you want to count the number of columns use:

Select count(column_name) FROM table name.

If you want the sum of column values then use:

Select SUM(column_name) FROM table name.
Sign up to request clarification or add additional context in comments.

2 Comments

@RohanKumar OP can write code, if he can't don't feed him with code.
No problem, I can write php code, I just need this "select" prompt, so it's OK :-)
2

UPDATE with PHP Code

If you want to count you can do it like this:

    $query = "SELECT COUNT(*) FROM table_name"

    // Print out result
    while($row = mysql_fetch_array($result)){
    echo "Total count". $row['COUNT(*)'];
}

If you want to get the sum of one column, you can do like this:

$query = "SELECT SUM(column_name) FROM table_name"
// Print out result
    while($row = mysql_fetch_array($result)){
    echo "Total sum". $row['SUM(column_name)'];
}

Comments

1

Or maybe SUM is what you really want:

Select SUM(column_name) FROM tablename

Comments

0

You can use this for counting 1 row in your database:

<?php

$query = "SELECT COUNT(price) FROM yourtable ";

?>

Then you can use $query in your code to show the results.

In mysql (phpmyadmin) you can just do:

SELECT COUNT(price) FROM yourtable

Comments

0

Try mysqli_result() like,

<?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if ($result = $mysqli->query("SELECT COUNT(price) as total FROM tablename")) {

        /* Get field information for column 'SurfaceArea' */
        $finfo = $result->fetch_field_direct(1);
        printf("Total price:     %s\n", $finfo->total);
        $result->close();
    }
    /* close connection */
    $mysqli->close();
?>

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.