Ok, so I have a message system in my website which adds a message to a database with the sender's name and the reciever's name. The function for retrieving the message to be able to read the it works somewhat, except that it only displays one row of data. If there is 2 rows of data it displays the last row's data twice.
Here is my function for retrieving the message:
function getMessages($user) {
$hostname = "localhost";
$username = "";
$db_password = "";
$db_name = "tsn_database";
$mysqli = @new mysqli($hostname, $username, $db_password, $db_name);
if(mysqli_connect_errno()) {
echo "Unable to connect";
} else {
$statement = $mysqli->prepare("SELECT * FROM messages WHERE sent_to='$user'");
$statement->execute();
$statement->bind_result($id, $date_sent, $sent_by, $sent_to, $message, $sent_by_delete, $sent_to_delete);
$statement->fetch();
$statement->close();
$query = $mysqli->query("SELECT * FROM messages WHERE sent_to='$user'");
if($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
global $result;
$result = '<p>From: '. $sent_by .'<br/>'
.'Date Received: '. $date_sent .'<br/>'
.'<hr/>'
. $message . '<br/><br/>'
.'<a href="?cmd=delete&id='.$id.'">Delete Message</a></p>';
}
} else {
global $result;
$result = "No Messages!";
}
return;
}
}
This is my page that should display the messages:
<?php
session_start();
$hostname = "localhost";
$username = "";
$db_password = "";
$db_name = "tsn_database";
$session = $_SESSION['valid_user'];
$mysqli = @new mysqli($hostname, $username, $db_password, $db_name);
if(mysqli_connect_errno()) {
echo "Unable to connect";
} else {
$sql = "SELECT * FROM user_information WHERE user_email = '$session'";
$statement = $mysqli->prepare($sql);
$statement->execute();
$statement->bind_result($id, $name, $surname, $gender, $contact, $email, $country, $age, $picture_path, $password);
$statement->fetch();
$statement->close();
}
include_once("Functions.php");
if($_GET['cmd'] == 'delete') {
deleteMessages($_GET['id']);
}
$user = $name;
getMessages($user);
?>
<table>
<tr>
<td> <?php echo $result ?> </td>
</tr>
</table>
The code above still has other pieces of code but it has nothing to do with the functions. Just let me know if you might need it.
I am thinking that there might be something wrong with my while loop in the functions script. But I cant figure out how to fix this.. I am still a student with much to learn but really need this piece of code to work. When the messages are retrieved, as I mentioned the second row is displayed twice. and if i delete the second message both of the second messages(which are the same) disappears and message one is left there.. They were printed over message one..
But it should display as follows.
message 1
message 2
and not as:
message 1(hidden under message 2)
message 2
message 2
Hope you understand what I am trying to say.
Thanks in advance,
Chris