gavin gavin - 3 months ago 23
PHP Question

selecting Max(val) from a sql resource in php

I have a sql result that looks like this:

MAX(val) | instance
17410742.00 | 0

I need to loop through it in php but I can't seem to select the Max(val) column. Usually I would do a something like this:

foreach ($sqlmax as $maxrow){

Which returns the 'instance' value, but I can't get the syntax to retrieving the Max(val) as

foreach ($sqlmax as $maxrow){

doesn't work. I get the error Notice: Undefined index:

How do I select the Max(val) result in the same way I can select the 'instance' value? Thanks


Use AS in your SQL Query:

SELECT MAX(val) AS max_val, instance FROM table WHERE instance = 0;

Then you will be able to access the column as $myvar=$maxrow['max_val'];.

The query I wrote here is just an example, since you do not provide yours.

I will go ahead an assume you use mysql and will provide a link to MySQL docs:

A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses. For example:

SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable ORDER BY full_name;