Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple row values out of MySQL table

Tags:

php

mysql

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!

like image 614
Annoying Bot Avatar asked Jun 05 '13 07:06

Annoying Bot


People also ask

How do I select multiple rows in a table?

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.

How do I combine multiple rows into one in MySQL?

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.

Can MySQL handle millions of rows?

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.


2 Answers

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.

like image 50
BlitZ Avatar answered Sep 22 '22 17:09

BlitZ


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

SELECT SUM(column name) FROM table WHERE condition
like image 38
Robert Seddon-Smith Avatar answered Sep 22 '22 17:09

Robert Seddon-Smith