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!
Select multiple items in a table or list using shift-click and ctrl-click. This can be useful to add multiple resources to a graph or modify multiple items at a time. To select a range of items, hold down the shift key and then click on the top item followed by the bottom item.
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.
Millions of rows is fine, tens of millions of rows is fine - provided you've got an even remotely decent server, i.e. a few Gbs of RAM, plenty disk space. You will need to learn about indexes for fast retrieval, but in terms of MySQL being able to handle it, no problem. Save this answer. Show activity on this post.
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.
Just use a SUM()
in your SQL. This generic sql should work:
SELECT SUM(column name) FROM table WHERE condition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With