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
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.
2 Comments
Yogesh Suthar
@RohanKumar OP can write code, if he can't don't feed him with code.
Štěpán Němejc
No problem, I can write php code, I just need this "select" prompt, so it's OK :-)
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
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();
?>