为什么你不应该使用mysql_fetch_assoc超过一次


Why you should not use mysql_fetch_assoc more than 1 time?

有些人说你不应该多次使用mysql_fetch_assoc,为什么呢?

。:我想显示两个表,一个是付费会员的用户,另一个是没有付费的用户,所以不是查询数据库2次,而是查询它一次,得到两种类型的用户的$result变量,然后我运行循环mysql_fetch_assoc,看看list['membership'] = 'paid'是否回显…

第二次我循环mysql_fetch_assoc,看看是否list['membership'] = 'free'然后echo…

考虑到注册和未注册的用户数量相等,什么使用更少的资源

把查询结果集想象成一根香肠,把mysql_fetch_assoc()想象成从香肠上切下一片的刀。每次你取出一排香肠,另一根香肠就被切掉,而且总是新的香肠。

你不能再把之前切好的那块切下来,因为它已经被吃掉了。

引用自type85 (link):

请注意,你传递给这个函数的资源结果可以被认为是通过引用传递的,因为资源只是一个指向内存位置的指针。

因此,在将指针重置回起始位置之前,您不能在同一脚本中循环遍历资源结果两次。

例如:

<?php
// Assume We Already Queried Our Database.
// Loop Through Result Set.
while( $queryContent = mysql_fetch_row( $queryResult ) {
    // Display.
    echo $queryContent[ 0 ];
}
// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.
// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.
// So the following code, if executed after the previous code
// segment will not work.
while( $queryContent = mysql_fetch_row( $queryResult ) {
    // Display.
    echo $queryContent[ 0 ];
}
// Because $queryContent is now equal to FALSE, the loop
// will not be entered.
?>

唯一的解决方案是重置指针,使其在第二个代码段之前再次指向第一行,所以现在完整的代码将如下所示:

<?php
// Assume We Already Queried Our Database.
// Loop Through Result Set.
while( $queryContent = mysql_fetch_row( $queryResult ) {
    // Display.
    echo $queryContent[ 0 ];
}
// Reset Our Pointer.
mysql_data_seek( $queryResult );
// Loop Again.
while( $queryContent = mysql_fetch_row( $queryResult ) {
    // Display.
    echo $queryContent[ 0 ];
}
?>

当然,您必须做额外的检查,以确保结果中的行数不是0,否则mysql_data_seek本身将返回false,并将引发错误。

还请注意,这适用于所有获取结果集的函数,包括mysql_fetch_row, mysql_fetch_assosmysql_fetch_array

当有人说您不能两次调用mysql_fetch_assoc()时,他们的意思是针对相同的资源。传递给mysql_fetch_assoc()的资源结果是通过引用完成的。在第二次使用mysql_fetch_assoc()之前,你需要重置指针的位置。

编辑:要做到这一点,请尝试使用mysql_data_seek() .

看来您要做的是将查询结果视为数组(字段)的数组(行)。但这并不是mysql库所提供的。实际上,我经常做的是将行复制到数组的数组中(只是在mysql_fetch上循环直到为空),然后使用PHP为此目的提供的数组函数对我自己的行集执行我想要的操作。这还可以最大限度地减少表的锁定时间。