duanlie7962 2014-05-15 11:39
浏览 154
已采纳

PHP - 在循环中多次使用mysql_fetch_assoc()。

I'm working on a really simple email notification system for newly added comments. It works like this:

  1. loop through project users
  2. for each user, loop through all comments written in the last hour
  3. if there are any comments that are not written by the user, push them to an array
  4. if comment array is not empty, send an email to the user

Here's some of the code:

<?php
$users_query = mysql_query("SELECT * FROM users");

$comments_query = mysql_query("SELECT * FROM comments c, users u WHERE c.date > DATE_SUB(NOW(), INTERVAL 1 HOUR) and c.user_id = u.id");

while ($user = mysql_fetch_assoc($users_query)) {
   $commentsArr = array();  

   while ($comment = mysql_fetch_assoc($comments_query)) {
      if ($comment['email'] != $user['email']) {
         array_push($commentsArr, $comment['comment']);
      }
   }

   // send $commentsArr by email to $user['email']
}
?>

The problem is that the same mysql_fetch_assoc cannot be used multiple times on a single page. I tried reseting the pointer using mysql_data_seek($comments_query, 0); but that just threw the following error:

Warning: mysql_data_seek() [function.mysql-data-seek]: Offset 0 is invalid for MySQL result index 4 (or the query data is unbuffered)

Are there any other ways of handling this? All other people with similar questions were advised to join their tables instead of splitting them up. I don't think I can do that since I have to go through all users first, so if I join them, I'll have more rows than users.

Anyway, is there a way to loop through the comments while inside a loop?

  • 写回答

3条回答 默认 最新

  • doubengshao8872 2014-05-15 13:12
    关注

    I switched from mysql to mysqli and now mysqli_data_seek($comments_query, 0); works as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站