ToddN
ToddN

Reputation: 2961

php MAX MySQL Query not echoing

The below displays nothing. I simply want to pull the MAX number between two dates. The SQL Query actually works, and the dates are fine as they are used in other queries. It just doesn't seem to work with the MAX selector.

$con = mysql_connect("host","user","pw");
mysql_select_db("db", $con);

//Other queries before this..
$query5="SELECT MAX(TOTALVISITS) FROM mytable WHERE DATE between '$mystartdate' and '$thedbdate'";

$result5=mysql_query($query5);
mysql_close();

$maxtotal=mysql_result($result5);

echo $MAX TOTAL: " . $maxtotal;

Upvotes: 0

Views: 434

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270717

First, don't call mysql_close() after mysql_query(). Your result set won't be available for fetch.

$result5=mysql_query($query5);
// DON'T DO THIS!
//mysql_close();

mysql_result() takes at least two parameters - the resource and the row you want to retrieve, and optionally the column you want to retrieve. Since you have only one, the column can technically be omitted.

// Get the first column of the first row from the result set.
$maxvisits = mysql_result($result5, 0, 0);

Note, it is good practice to assign an alias to a calculated or aggregate column:

$query5="SELECT MAX(TOTALVISITS) AS maxvisits FROM mytable WHERE DATE between '$mystartdate' and '$thedbdate'";
//------------------------------^^^^^^^^^^^^^^

This makes it easier to use functions like mysql_fetch_assoc(), which can be a little more flexible than mysql_result():

$row = mysql_fetch_assoc($result5);
echo $row['maxvisits'];

Upvotes: 1

Related Questions