I have an array with values declared in a while statement at the end of function fetch_conversation_messages in a backend file for a private message system. However, the array that is revealed is blank (other than the echos and print_rs that I have used for debugging).
I am very new to this forum, PHP and MySQL, so please help me.
Thank you in advance.
// 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_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'],
);
echo mysql_num_rows($result);
var_dump($row);
}
echo count($messages);}
Also, there is a foreach error (written below as a comment on the first answer) in view_conversation.page.inc.php, which is this page:
<?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
}
?>