0

I am trying to write a PHP function which gets the sum of values in 1 column of a table. MY SQL statement works just fine. However, when I write my function and attempt to echo the variable into my HTML code, it returns '0'.

Here is my function:

function get_asset_value($org_ID) {
global $db;
$query = "SELECT SUM(asset_value) FROM assets
          WHERE org_ID = '$org_ID'";
$asset_sum = $db->query($query);
$asset_sum = $asset_sum->fetch();
return $asset_sum;

In my HTML, I have the following:

<?php echo $asset_sum; ?>

I'm not sure if this has to do with the "fetch" portion of my function. I really don't know what fetch does but I tried copying/modifying this piece of code from a working function (which doesn't return the sum, but it is a select statement).

Thank you!

1
  • You're wide open to SQL injection , maybe you could use prepared statement ? Commented Nov 14, 2011 at 16:43

2 Answers 2

1

In addition to

SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';
...
return $asset_sum['the_sum']

by Brad,

you better do

$safer = mysql_real_escape_string($org_ID);

then do,

SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$safer';
...
return $asset_sum['the_sum']
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';

...

return $asset_sum['the_sum'];

The issue is, you are returning an entire record, rather than just the field you want.

Also, judging by the way you are inserting that ID in your query, I suspect you are open to SQL injection. You should really learn to do prepared queries with PDO.

1 Comment

Thanks, Brad. That totally worked. I really appreciate the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.