Reputation: 593
How would you go about getting the first and last value from a sql query . I want the highest and lowest vaue of variable $integer1, so I have ordered them in Ascending order in my sql query, but now need to pull them out of the array as first and last items. I tried this but it didn't work:
$first = reset($result);
$last = end($result);
Also, In the sql query I select string1, string2 and integer1
I want to order by integer1 and then print out first and last (both strings)
First echo $string 1. " " . /4string2;
Last echo $string 1. " " . /4string2;
Upvotes: 0
Views: 3039
Reputation: 4089
Asuming you want the min and the max value of a field in SQL.
Instead of fetching all the rows from your table and take the first and the last row in PHP, do it in SQL !
SELECT MIN(your_field), MAX(your_field) FROM your_table WHERE conditions GROUP BY field1,field2
Upvotes: 3
Reputation: 116
You need to use array_shift and array_pop methods http://www.php.net/manual/en/function.array-pop.php http://www.php.net/manual/en/function.array-shift.php
Upvotes: 0
Reputation: 2010
array_shift give you the first row, array_pop the last one
$first = array_shift($rows) ;
$last = array_pop($rows) ;
Upvotes: 2