user3506938
user3506938

Reputation: 593

get first and last value form a mysql results array

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

Answers (3)

fluminis
fluminis

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

abdoulcool
abdoulcool

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

Pierre Granger
Pierre Granger

Reputation: 2010

array_shift give you the first row, array_pop the last one

$first = array_shift($rows) ;
$last = array_pop($rows) ;

Upvotes: 2

Related Questions