php - 如何在 MySQL 查询结果中查找特定行?

标签 php mysql

所以我这样做是为了检索我的整个表:

$result = mysql_query( 'SELECT * FROM mytable' );

然后,在我的 PHP 页面的另一部分,我执行另一个查询(针对特定行):

$result2 = mysql_query( 'SELECT * FROM mytable WHERE id = ' . $id );
$row = mysql_fetch_array( $result2 );

因此,我正在执行两个查询。但是,我真的不必那样做,对吗?我的意思是,我在第二个查询中检索的行已经存在于 $result(我的第一个查询的结果)中,因为它包含我的整个表。

因此,我不想执行第二个查询,而是想直接从 $result 中提取所需的行(同时保持 $result 本身完好无损)。

我该怎么做?


好的,这就是我实现它的方式:

function getRowById ( $result, $id )
{
    while ( $row = mysql_fetch_array( $result ) ) {
        if ( $row['id'] == $id ) {
            mysql_data_seek( $result, 0 );
            return $row;
        }
    }
}

最佳答案

在第一次查询缓存数据后:

$rows = array();
while($row=mysql_fetch_array($result) {
    $rows[$row[0]] = $row;
}

然后简单地访问数据使用:

$row = $rows[$id];

id 必须是您所在领域的第一个列才能起作用。

关于php - 如何在 MySQL 查询结果中查找特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164035/

相关文章:

php - MySQL 用 faker 生成的结果更新表

java - 为什么我的长整数会稍微改变一点?

php - 交响乐 2.3 : CollectionRegionDoctrineCommand not found when update vendors and clear cache

php - PHP 中的 Office 365 API

php - 使用codeigniter在mysql中插入多行: it inserts only one row and in that one row stores only one first character

c# - Nhibernate 渴望与 parent 一起获取 child 的 child

mysql - 创建单个查询以从表中获取数据作为单独的行

php - 使用一个事务 ID 在数据库中进行多次插入

php - Summernote - 图片 url 而不是 Base64

php - 根据同一表中的其他值标记/更新值