Log in

View Full Version : Resolved Echo and calculate data from db



john1991
05-11-2014, 09:02 AM
Hello,

I am trying to echo results from mysql.

I have a table 'rb_pallet_record' and a column 'quantity' which records the amount of products.

What I would like to do is calculate all of the quantity data echoing the total.

ie.

quantity

5
8
7
5

total = 25

here is the php i am working with


<?php $link = mysql_connect('localhost', 'root', 'taycon');

if (!$link) { die('Could not connect: ' . mysql_error());}echo '';mysql_select_db("rb");?>



<?php
$sql = "select count(quantity) from rb_pallet_record";
$result=mysql_query($sql,$link)or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_NUM);
echo $row[0];
?>



Thanks

fastsol1
05-11-2014, 01:04 PM
This should be a simple change.


$sql = "SELECT SUM(`quantity`) as `total` FROM `rb_pallet_record`"; // You really should capitalize the key words in a sql string to make it more readable. Plus surrounding your table names and column names with `backticks` will make sure the query doesn't accidentally think those words mean something else besides table and column names.
$result=mysql_query($sql)or die(mysql_error()); // There is no need for the $link in the query call with the basic mysql_query.
$row = mysql_fetch_assoc($result); // The assoc array is easier to use and does not contain the extra indexed array. Also the MYSQL_NUM is not needed, I've never actually seen that used.
echo $row['total']; // Output as 'total' since that is what it's not referenced as in the query.

As a last side note, you really should stop using the mysql functions as they are now deprecated and will be removed in the future from PHP. You should be using either mysqli or PDO which is the more preferred method.

john1991
05-11-2014, 01:31 PM
Thank you for your help and pointers definitely a learning curve!