【问题标题】:Warning: Invalid argument supplied for foreach() PHP MySQL private message system警告:为 foreach() PHP MySQL 私人消息系统提供的参数无效
【发布时间】:2014-03-14 04:29:41
【问题描述】:

我是这个论坛的新手,也是 PHP 和 MySQL 的新手。打开名为 view_conversation.page.inc.php 的页面时出现以下错误:

    <?php

$errors = array();
$valid_conversation = (isset($_GET['conversation_id']) && validate_conversation_id($_GET['conversation_id']));
if ($valid_conversation === false){
        $errors[] = 'Invalid Conversation ID.';
}
if (isset($_POST['message'])){
        if (empty($_POST['message'])){
                $errors[] = 'You must enter a message.';
        }

        if (empty($errors)){
                add_conversation_message($_GET['conversation_id'], $_POST['message']);
        }
}

if (empty($errors) === false){
        foreach ($errors as $error){
        }
}
echo $error;

if ($valid_conversation){
        /*if (isset($_POST['message'])){
                update_conversation_last_view($_GET['conversation_id']);*/
                $messages = fetch_conversation_messages($_GET['conversation_id']);
                print_r($messages);
        /*}else{
                $messages = fetch_conversation_messages($_GET['conversation_id']);
                update_conversation_last_view($_GET['conversation_id']);
        }*/

}
?>
<a href="index.php?page=inbox">Inbox</a>
<a href="index.php?page=logout">Logout</a>

        <form action="" method="post">
                <p><textarea name="message" rows="10" cols="110"></textarea></p>
                <p><input type="submit" value="Add Message" /></p>
        </form>

        <?php
        foreach ($messages as $message){
        ?>
        <?php if ($message['unread']) echo 'unread'; ?>
        <p class="name">Username: <?php echo $message['user_name']; ?></p>
        <p class="text">Date: <?php echo date('d/m/Y H:i:s', $message['date']); ?></p>
        <p>Message: <?php echo $message['text']; ?></p>

<?php

}
?>

它链接到名为 private_message.inc.php 的页面中的函数:

    <?php

    // Fetches a summary of the conversations.
    function fetch_conversation_summary(){
            $sql = "SELECT
                                    `conversations`.`conversation_id`,
                                    `conversations`.`conversation_subject`,
                                    MAX(`conversations_messages`.`message_date`) AS `conversation_last_reply`,
                                    MAX(`conversations_messages`.`message_date`) > `conversations_members`.`conversation_last_view` AS `conversation_unread`
                            FROM `conversations`
                            LEFT JOIN `conversations_messages` ON  `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
                            INNER JOIN `conversations_members` ON `conversations`.`conversation_id` = `conversations_messages`.`conversation_id`
                            WHERE `conversations_members`.`user_id` = {$_SESSION['user_id']}
                            AND `conversations_members`.`conversation_deleted` = 0
                            GROUP BY `conversations`.`conversation_id`
                            ORDER BY `conversation_last_reply` DESC";

            $result = mysql_query($sql);

            $conversations = array();

            while (($row = mysql_fetch_assoc($result)) !== false){
                    $conversations[] = array(
                            'id'                            => $row['conversation_id'],
                            'subject'                       => $row['conversation_subject'],
                            'last_reply'            => $row['conversation_last_reply'],
                            'unread_messages'       => ($row['conversation_unread'] == 1),
                    );
            }

            return $conversations;
    }

// Fetches all of the messages in the given converstion.
function fetch_conversation_messages($conversation_id){
        $conversation_id = (int)$conversation_id;

        $sql = "SELECT
                                `conversations_messages`.`message_date`,
                                `conversations_messages`.`message_date` > `conversations_members`.`conversation_last_view` AS `message_unread`,
                                `conversations_message`.`message_text`,
                                `users`.`user_name`
                        FROM `conversations_messages`
                        INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
                        INNER JOIN `conversations_members` ON `conversations_messages`.`conversation_id` = `conversations_members`.`conversation_id`
                        WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
                        AND `conversations_members`.`user_id` = {$_SESSION['user_id']}
                        ORDER BY `conversations_messages`.`message_date` DESC";

        $result = mysql_query($sql);

        $messages = array();

        while (($row = mysql_fetch_assoc($result)) !== false){
                $messages[] = array(
                        'date'          => $row['message_date'],
                        'unread'        => $row['message_unread'],
                        'text'          => $row['message_text'],
                        'user_name' => $row['user_name'],
                );
        }

        return $messages;
}

/*function fetch_conversation_messages($conversation_id){
        $conversation_id = (int)$conversation_id;

        $sql = "SELECT
            `conversations_messages`.`message_date`,
            `conversations_messages`.`message_text`,
            `users`.`user_name`
        FROM `conversations_messages`
        INNER JOIN `users` ON `conversations_messages`.`user_id` = `users`.`user_id`
        WHERE `conversations_messages`.`conversation_id` = {$conversation_id}
        ORDER BY `conversations_messages`.`message_date` DESC";

        $result = mysql_query($sql);
        var_dump($result);
        $messages = array();

        while (($row = mysql_fetch_assoc($result)) !== false){
                $messages[] = array(
                        'date'          => $row['message_date'],
                        'unread'        => $row['message_unread'],
                        'text'          => $row['message_text'],
                        'user_name'     => $row['user_name'],
                );
                        var_dump($row);

        }
echo count($messages);}*/


    // Sets the last view time to the current time for the given conversation.
    function update_conversation_last_view($conversation_id){
            $conversation_id = (int)$conversation_id;
            $time = time() + 18000;
            $sql ="UPDATE `conversations_members`
                            SET `conversation_last_view` = {$time}
                            WHERE `conversation_id` = {$conversation_id}
                            AND `user_id` = {$_SESSION['user_id']}";

            mysql_query($sql);     
    }

     // Creates a new conversation, making the given users a member.
    function create_conversation($user_ids, $subject, $body){
            $subject        = mysql_real_escape_string(htmlentities($subject));
            $body           = mysql_real_escape_string(htmlentities($body));

            mysql_query("INSERT INTO `conversations` (`conversation_subject`) VALUES ('{$subject}')");

            $conversation_id = mysql_insert_id();

            $sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`, `message_date`, `message_text`)
                            VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$body}')";

            mysql_query($sql);

            $values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");

            foreach ($user_ids as $user_id){
                    $user_id = (int)$user_id;

        $values = array("({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), 0)");            }

            $sql = "INSERT INTO `conversations_members` (`conversation_id`, `user_id`, `conversation_last_view`, `conversation_deleted`)
                            VALUES " . implode(", ", $values);

                            mysql_query($sql);
    }


    // Checks to see if the given user is a member of the given conversation.

   function validate_conversation_id($conversation_id){
   $conversation_id = (int)$conversation_id;

   $sql = "SELECT COUNT(1)
   FROM `conversations_members`
   WHERE `conversation_id` = {$conversation_id}
   AND `user_id` = {$_SESSION['user_id']}
   AND `conversation_deleted` = 0";

   $result = mysql_query($sql);
   return(mysql_result($result, 0) == 1);
   }
    // Adds a message to the given conversation.
    function add_conversation_message($conversation_id, $text){
            $conversation_id        = (int)$conversation_id;
            $text                   = mysql_real_escape_string(htmlentities($text));

            $sql = "INSERT INTO `conversations_messages` (`conversation_id`, `user_id`,     `message_date`, `message_text`)
                            VALUES ({$conversation_id}, {$_SESSION['user_id']}, UNIX_TIMESTAMP(), '{$text}')";

            mysql_query($sql);

            mysql_query("UPDATE `conversations_members` SET `conversation_deleted` = 0 where `conversation_id = {$conversation_id}");
    }

// Deletes (or marks as deleted) a given conversation.
function delete_conversation($conversation_id){
            $conversation_id = (int)$conversation_id;

            $sql = "SELECT DISTINCT `conversation_deleted`
                            FROM `conversations_members`
                            WHERE `user_id` != {$_SESSION['user_id']}
                            AND `conversation_id` = {$conversation_id}";

            $result = mysql_query($sql);

            //if (mysql_num_rows($result) == 1 && mysql_result($result, 0) == 1){
            if (mysql_num_rows($result) == 0){
                    mysql_query("DELETE FROM `conversations` WHERE `conversation_id` = {$conversation_id}");
                    mysql_query("DELETE FROM `conversations_members` WHERE `conversation_id` = {$conversation_id}");
                    mysql_query("DELETE FROM `conversations_messages` WHERE `conversation_id` = {$conversation_id}");
            }else{
                    $sql = "UPDATE `conversations_members`
                                    SET `conversation_deleted` = 1
                                    WHERE `conversation_id` = {$conversation_id}
                                    AND `user_id` = {$_SESSION['user_id']}";

                    mysql_query($sql);

            }
    }
    ?>

请帮帮我。

【问题讨论】:

标签: php mysql function foreach arguments


【解决方案1】:

这意味着您正在尝试使用foreach 循环遍历数组,但是数组中没有任何内容,或者您​​尝试循环遍历不是数组的内容(如字符串)。 PHP 错误应该给你一个行号,以便你可以看到 foreach 被调用的位置。

【讨论】:

  • 是的,第 45 行。你知道如何解决这个问题吗?
  • 好的,所以第 45 行是foreach ($messages as $message){,这意味着它无法循环遍历变量$messages。在第 27 行,您正在设置 $messages,但仅设置 if ($valid_conversation){。您应该输入一个else 来说明$valid_conversation 是否未评估,然后将$messages 设置为一个空数组。 $messages = array();
  • 我试过了,但我仍然得到与 Array ( ) 1 相同的输出,并出现下面的 foreach 错误
  • 好的,那就按照 Alireza Fallah 在他的回答中建议的去做。在尝试循环之前,您应该检查您尝试循环的内容是否已设置。
【解决方案2】:

此警告错误表示您正在尝试循环遍历 非数组变量,或 空数组强> .

为了解决它,在你的 foreach 之前放一个 if, 像这样:

$messages = ...
if($messages){
   foreach($messages as $message){
      // do something
   }
}

【讨论】:

  • 空数组不会引起警告,也不是所有非数组都会引起警告(它必须是数组或 Traversable 的实例)。
  • 我用 if(isset($messages){ 语句尝试过(可能实现不正确),但同样,错误仍然相同
  • 你能给我一个关于变量的例子吗?直到两周前我才知道 mysql 是什么!
  • 不要使用isset,试试我在回答中所说的
  • 对不起,if($messages){ 出现在所有代码之前,我只是忘了复制它\
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多