5

I'm a total noob at PHP but I'm trying, with the information I can find, to build a script that reads multiple rows from a MySQL table. Each row only contains a number. Let me give an example:

Every ID in the table has a row called "number".

ID| NUMBER
1 | 8
2 | 12
3 | 6
4 | 9

Now I need a script that - for example - takes ID 1, 2, and 4 and calculates the total amount 8 + 12 + 9 = 29. 3 is not interesting and I don't want that row in the calculation process. Next this total number needs to be output to a blank website page, so it only shows the total number without anything else.

Examples would be more than welcome and greatly appreciated!

4

2 回答 2

6

Check out sql SUM() aggregate function and IN comparison operator:

SELECT SUM(`number`) FROM `table` WHERE `id` IN (1,2,4);

UPDv1:

<?php
// hostname, username, password and database should be replaced with actual values.
$dbms = mysqli_connect('hostname', 'username', 'password', 'database');

if($dbms->connect_errno)die('MySQL connection error: ' . $dbms->connect_error);

// table should be replaced with actual table name.
$result = $dbms->query('SELECT SUM(`number`) as `amount` FROM `table` WHERE `id` IN (1,2,4)');

if($dbms->errno)die('MySQL error: ' . $dbms->error);

$row = $result->fetch_assoc();

echo $row['amount'];
?>

Also, check MySQLi driver for PHP is installed.

于 2013-06-05T07:55:53.633 回答
2

Just use a SUM() in your SQL. This generic sql should work:

SELECT SUM(column name) FROM table WHERE condition
于 2013-06-05T07:54:53.897 回答