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条)

报告相同问题?

悬赏问题

  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal