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){
$myvar=$maxrow['instance'];
}
Which returns the 'instance' value, but I can't get the syntax to retrieving the Max(val) as
foreach ($sqlmax as $maxrow){
$myvar=$maxrow['Max(val)'];
}
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
Assign a column name in your query, so you can access the field easier:
SELECT MAX(val) AS max_value ....
Then you can access it with
$myvar=$maxrow['max_value']
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;
Simply do it like
select max(val) as mval
and access it like
$maxrow['mval']
Just providing an alternate answer, in case you don't want (or are unable to) use AS
.
The problem here was that the key of the array is case sensitive, so you have to use $maxrow['MAX(val)']
instead of $maxrow['Max(val)']
.
SELECT MAX(val) AS instance
Access this
foreach ($sqlmax as $maxrow){
$myvar=$maxrow['instance'];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.