php 获取mysql资源字符串的第一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4614613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:41:49  来源:igfitidea点击:

Getting the first row of the mysql resource string?

phpmysqldatabase

提问by mrN

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 * 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?

现在,如何只提取第一行?

回答by David Powers

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().

使用 mysql_fetch_assoc() 不仅获取一行,还将结果集的内部指针移动到下一行。要将结果资源重置为第一行,您需要使用 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
}

回答by Anush Prem

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

有关 mysql_data_seek 的更多信息:PHP: mysql_data_seek - 手册

回答by Nourein

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
    }
}

回答by Lightness Races in Orbit

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:

每次调用时mysql_fetch_assoc($result),都会得到一行。因此,不要在循环中重复执行,只需执行一次:

$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!

免责声明:这可能是更漂亮的代码,但您明白了!