while($row = mysql_fetch_array($query)) doesn't work in second time

前提是你 提交于 2020-02-01 09:17:20

问题


I have:

$query = mysql_query("SELECT ... ");
while($row = mysql_fetch_array($query)) { first time used; }
...
while($row = mysql_fetch_array($query)) { second time used; }

In second time it doesn't work. Why?


回答1:


That's because the internal data pointer has reached its end. To reread the query, either rewind the pointer with mysql_data_seek(), or reissue the query.




回答2:


A MySQL result resource has an internal pointer, much like a PHP array, and when you have run through it once, the pointer is at the end. You can reset the data pointer using mysql_data_seek():

while ($row = mysql_fetch_array($query)) {
  // First time used
}
mysql_data_seek($query, 0);
while ($row = mysql_fetch_array($query)) {
  // Second time used
}

...but what is arguably a better/more "standard" approach is to run through the pointer once, store the results in a temporary array and then you can release the memory used by the results and loop the data as an array:

// Do the query
$query = mysql_query("SELECT ... ");

// Cache the results in an array
$results = array();
while ($row = mysql_fetch_array($query)) {
  $results[] = $row;
}

// Free the result resource
mysql_free_result($query);

foreach ($results as $row) {
  // First time used
}
foreach ($results as $row) {
  // Second time used
}

As a side note, it is more resource efficient to use mysql_fetch_assoc() or mysql_fetch_row() - almost every use case only calls for mysql_fetch_assoc(), it is very uncommon that you indexed keys for a MySQL result, and even less common that you need both indexed and associative.




回答3:


It won't work the second time because you have already retrieved all of the rows. Therefore it returns false.




回答4:


Reset the result pointer to the beginning of the result set before looping the second time using mysql_data_seek()

mysql_data_seek($query,0)



回答5:


You've retrieved all the rows so you'll have to run another query or you can shove the values from your first loop into an array and then output that array for the second time you want to display the same data.

Or use mysql_data_seek()



来源:https://stackoverflow.com/questions/9698944/whilerow-mysql-fetch-arrayquery-doesnt-work-in-second-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!