Getting the first row of the mysql resource string?
Here is my problem. I need more than one row from the database, and i need the first row for certain task and then go through all the list again to create a record set.
$query = "SELECT开发者_如何学C * FROM mytable";
$result = mysql_query($query);
$firstrow = //extract first row from database
//add display some field from it
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
Now, how to extract just the first row?
Using mysql_fetch_assoc() not only fetches a row, it also moves the internal pointer of the result set to the next row. To reset the result resource to the first row, you need to use mysql_data_seek().
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
$firstrow = mysql_fetch_assoc($result);
// reset the result resource
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
If you want to get all the rows from the first one again then try the following
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = mysql_fetch_assoc ($result){
$firstRow = $row;
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)) {
//display all of them
}
}
More about mysql_data_seek here: PHP: mysql_data_seek - Manual
you can use Object oriented style :
$query = "SELECT * FROM mytable";
$result = mysql_query($query);
if ( $row = $result->fetch_assoc()){
$firstRow = $row;
mysql_data_seek($result, 0);
while( $row = $result->fetch_assoc()) {
//display all of them
}
}
Each time you call mysql_fetch_assoc($result)
, you get a row. So, instead of doing it repeatedly in a loop, just do it once:
$result = mysql_query("...");
if ($row = mysql_fetch_assoc($result)) {
$firstRow = $row;
while ($row = mysql_fetch_assoc($result)) {
// all the rest
}
}
Disclaimer: this could be prettier code, but you get the idea!
精彩评论