I am learning PHP and have been reading some books and tutorials, and I have started working on a php messaging site just to learn some techniques. The problem is that i cannot work out how to refresh the list of messages that a user is displayed.
For example, when a user is sent a message they will not receive it until their webpage is refreshed. I realise that i could simply refresh the page on a interval but then if a long message is being written chances are the page will refresh before the message is sent.
As i haven't been able to find a solution i can get my head around online, thought i would ask on here :) My question to the internet is: Is there a way to refresh one section of the page, or keep drawing data from a database and echo it to the user.
Here is the code for the page which displays the messages to the user.
<html>
<head>
<title>Conversations - Hepburn's Messager</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<?php include 'title_bar.php'; ?>
<div class='container-fluid'>
<h3>Conversations - Hepburn's Messager</h3>
<?php include 'message_title_bar.php' ?>
<?php
$my_id = $_SESSION['user_id'];
?>
<div>
<?php
if(isset($_GET['hash']) && !empty($_GET['hash'])) {
$hash = $_GET['hash'];
$message_query = mysql_query("SELECT from_id, message FROM messages WHERE group_hash='$hash'");
while($run_message = mysql_fetch_array($message_query)) {
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT username FROM users WHERE id='$from_id'");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['username'];
echo "<p><b>$from_username</b><br/>$message</p>";
setInterval(function(){
echo "hi!\n";
}, 1000);
}
?>
<br/>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$new_message = $_POST['message'];
mysql_query("INSERT INTO messages VALUES('', '$hash', '$my_id', '$new_message')");
header('location: conversations.php?hash='.$hash);
}
?>
<h4>Enter Message:</h4>
<textarea class='form-control' rows='6' cols='50' name='message'></textarea>
<input class='btn btn-primary btn-lg' type='submit' value='Send Message'/> <!-- problem -->
</form>
<?php
} else {
echo "<h4>Select a conversation:<h4>";
$get_con = mysql_query("SELECT hash, user_one, user_two FROM message_group WHERE user_one='$my_id' OR user_two='$my_id'");
while($run_con = mysql_fetch_array($get_con)){
$hash = $run_con['hash'];
$user_one = $run_con['user_one'];
$user_two = $run_con['user_two'];
if($user_one == $my_id){
$select_id = $user_two;
} else {
$select_id = $user_one;
}
$user_get = mysql_query("SELECT username FROM users WHERE id='$select_id'");
$run_user = mysql_fetch_array($user_get);
$select_username = $run_user['username'];
echo "<p><a href='conversations.php?hash=$hash'>$select_username</a></p>";
}
}
?>
</div>
</div>
</body>
</html>