How to write a query for PHP and MySQL?

MySQL Query SUM() function (in PHP)?

  • Hi, my problem is when I try to run the MySQL SUM() function through PHP it just returns a completely blank array. Here is my PHP code (modified): $var = mysql_query("SELECT SUM(uniques) FROM stats WHERE unqiues BETWEEN '1000' AND '2000'"); I have checked the table and table field names and they are completely correct, and multiple 'uniques' values are between 1000 and 2000. With SUM() it shouldnt be returning an Array at all, just one value. Its complicated what I'm trying to do but I need all of the 'uniques' values added together whos values are between 1000 and 2000. I have the most updated versions of PHP and MySQL installed on my server, just updated a few weeks ago and this is my first problem. Thanks.

  • Answer:

    The mysql_query() function returns a result handle (a reference to a list of results that then need retrieved), not a single value. To use your example (SQL statement changed to name the resulting field): $handle = mysql_query("SELECT SUM(uniques) AS myvalue FROM stats WHERE uniques BETWEEN '1000' AND '2000'"); // Check to see if we did something wrong if( !$handle ) { die( 'Error running query: ' . mysql_errno( $handle ) . ' ' . mysql_error( $handle ) ); } // Fetch the row $row = mysql_fetch_assoc( $handle ); // Grab the data we want out of the row $myvalue = $row['myvalue']; It may seem overly complicated, but it's very rare that you want just one single value out of a database. The functions are designed for retrieving row after row of data, each row containing multiple columns.

Ben Ja Min at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

"$var = mysql_query("SELECT SUM(uniques) FROM stats WHERE unqiues BETWEEN '1000' AND '2000'");" You've misspelled 'uniques' in your WHERE clause.

John A

how about removing the parens? $var = mysql_query "SELECT SUM(uniques) FROM stats WHERE unqiues BETWEEN '1000' AND '2000'";

PC

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.