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

时间:2014-05-15 11:39:25

标签: php

我正在开发一个非常简单的电子邮件通知系统,用于新添加的评论。它的工作原理如下:

  1. 循环项目用户
  2. 为每个用户循环浏览过去一小时内写的所有评论
  3. 如果有任何用户未写入的评论,请将其推送到数组
  4. 如果注释数组不为空,则向用户发送电子邮件
  5. 这里有一些代码:

    <?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']
    }
    ?>
    

    问题是在同一页面上不能多次使用相同的mysql_fetch_assoc。我尝试使用mysql_data_seek($comments_query, 0);重置指针,但这只是引发了以下错误:

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

    还有其他方法可以解决这个问题吗?所有其他有类似问题的人都被建议加入他们的桌子,而不是将他们分开。我不认为我可以做到这一点,因为我必须先通过所有用户,所以如果我加入他们,我的行数会比用户多。

    无论如何,有没有办法在循环内循环注释?

3 个答案:

答案 0 :(得分:1)

我从mysql切换到mysqli,现在mysqli_data_seek($comments_query, 0);按预期工作。

答案 1 :(得分:1)

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

$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");

$comments = mysql_fetch_array($comments_query)

foreach($user as $users) {
  $commentsArr = array();  

  foreach($comment as $comments) {
    if ($comment['email'] != $user['email']) {
     array_push($commentsArr, $comment['comment']);
    }
  }

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

答案 2 :(得分:0)

在while循环外部使用$ commentsArr数组:

 <?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");
    $commentsArr = array();  
    while ($user = mysql_fetch_assoc($users_query)) {


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

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