MySQL select first 5 rows after query
I have a mysql result (having many rows) that I will use later. For now, I only need to access (sum) the first 5 rows. The problem is that the rows were saved from the query using "AS", so now they can be accessed by using $row['name']
. How can I select the first 5 rows without using the "name" for each of them?
Is there any wa开发者_StackOverflow社区y for doing like so:
PHP:
for($i=0;$i<5;++$i)
echo $row[$i];
?
EDIT
Sorry, my question was wrong. Actually: How can I use the same $result 2 times without loosing the values by fetching the array?What do you use for working with DB? PDO? MySQLi? MySQL extension?
If you use MySQL extension (mysql_connect()
, mysql_query()
etc), you can use mysql_data_seek()
to move the internal row pointer of the MySQL result:
$res = mysql_query($sql);
if ( mysql_num_rows($res) ) {
// process first 5 lines
for ( $n = 0; $n < 5; ++$n ) {
$row = mysql_fetch_assoc($res);
if ( $row === false ) {
break;
}
// do something with $row
// ...
}
// reset pointer
mysql_data_seek($res, 0);
// process all rows
while ( $row = mysql_fetch_assoc($res) ) {
// do something with $row
// ...
}
}
mysql_free_result($res);
Another option would be to fetch all results into an array and then work with that array. I can't think of any benefit of holding MySQL resource opened.
$result = array();
while( $row = mysql_fetch_array($queryResult) ) {
$result[$row['primaryKey']] = $row; // index the $result according to any fieldValue(say primay key) so that you can access a single records without looping)
echo $row['name'];
}
use $result as many times as you want
you can use mysql query as
select * from table_name_ravi limit 0,5
just use this
I think you mix up things. $row['name']
accesses the column of a row with the name name sou you should work on your fetch function your while( $row = mysql_fetch_assoc($result) ) {}
精彩评论