Im developing a web chat and was wondering, when Im displaying recent messages how do I get individual usernames to display. For example: when i log in as a user and send a message, it shows that its from me, but when I log in as a different user, all the messages are from that particular user ? Im not sure how to make it show the different user names. Any help would be apreciated.

Recommended Answers

All 31 Replies

Well I think this as to do with your database schemmas. From you db schemas you can call a username that the message is tied to. Please can you paste your database schemma, so we can give you a good algorithm on how to get the username.

I have two tables, User= {username, password} and message={msg_id,message,sender} and I have been trying to have a foreign key but I dont know what to link with what ?

Member Avatar

MySQL doesn't insist on constraints (FKs), but anyway:

This all depends upon whether you want the usernames to be volatile or stored in your db for further use in another session. If the latter, then you'll need to store email data for when an user loses their password etc, and it gets a little more involved. Otherwise, I don't why you need a PW. Obviously, the 'just enter an username and start messaging' approach is a little dodgy, as you could get all manner of idiots ruining your nice chat app. So, it may be an idea to set up a more robust user table, so you can store email, ip address?, new password recovery question, etc.
This will also allow you to add features such as 'temp ban', 'permaban' and give certain users greater access rights, e.g. moderator, which will allow them to 'kick' naughty users. Anyway, I may be getting ahead of myself here.

If you have the following type of user table (simplified):


You can then just add the user_id as an 'FK':


I'm assuming you're using ajax to update the chat display?
Be aware that with many people chatting, each display refreshing every 10 seconds or so, that may cause significant activity.

There are a number of 'off-the-peg' solutions out there. BluImp's AJax Chat was a particular favourite of mine when I needed it. It seems to have seen considerable updating since then, so I can't comment much on it these days. You can get into the guts of the code and see how it's implemented.

Thanks, Im suppsoed to be able to block people too, I was trying to start off basic enough and understand what was happening. I don't think I know how to block specific users though.

Ok I tried to change my tables and confused myself even more. Is there any way for me to show indivual usernames with the tables i have ? Here is what I have so far (its not even nearly finished btw)

here is the code for the chat page, can anyone tell me why its not reloading itself?

//Start a session
    //If the session variable views is set we have a valid logged on user
    //Put the restricted page content here
    $_SESSION['views'] = $_SESSION['views']+ 1;
    echo "<h1>Restricted Access Page</h1><p>Welcome ".$_SESSION['userid']."! You have successfully logged in.";
    echo "<p>";
    echo '<p>Click here to <a href="session_killer2.php">logout</a>';
    //if the session variable views is NOT set we do not have a valid logged on user
    //Put the redirection here
    echo "<h1>Session Expired</h1>";
    echo "You will be redirected to the login page in 5 seconds";
    echo '<meta http-equiv="Refresh" content="5;url=login.php" />';

if(isset($_POST['Submit']))   //Check if message submitted
    //DB connection parameters
    include ('open.php');

    //Make the DB connection
    $connection = mysql_connect($dbhost, $dbuser, $dbpass) 
                or die("Error connecting to MySQL!!");
    mysql_select_db($dbname, $connection) or die("Unable to select DB!");

    //Get the values from the form
    $message = $_POST['msg'];
    $sender = $_POST['from'];

    //Set up and execute the INSERT query
    $query = "INSERT INTO messages (message,sender) VALUES ('$message','$sender')";
    mysql_query($query) or die('Error Inserting Values');   
<!--Page will not be CACHED -->
<meta http-equiv="cache-control" content="no-cache" />
<script type="text/javascript">
//Set up some variables to be used by the timer
var c=0;
var t;
var timer_is_on=0;  //timer status 0=off 1=on

//Timer functions
function timedCount(){
loadXMLDoc(); //each time this function is called the dynamic content is updated
if (timer_is_on)
    t=setTimeout("timedCount()",1000);  //Sets the interval of the timer

function doTimer()  { //Start timer
if (!timer_is_on)

function stopTimer() { //Stop timer

function loadXMLDoc(){

//Set up some variables
// req: handle for the request object
var req;

// urlToFetch: URL of the dynamic content 
// Note the randNum variable being added to make the request unique
// this is required to overcome caching at the browser
var urlToFetch = 'http://localhost:8080/AJAX/LECT/message.php?randNum=' + new Date().getTime();

//Create the appropriate request object for the browser being used: 
if (window.XMLHttpRequest)  //The XMLHttpRequest property is available on the window object. 
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  req=new XMLHttpRequest();
  {// code for IE6, IE5
  req=new ActiveXObject("Msxml2.XMLHTTP");

  if (req.readyState==4 && req.status==200)

  }"GET",urlToFetch,true);  //open(): Assigns method, destination URL, and other optional attributes of a pending request.
req.send(); //Sends an HTTP request to the server and receives a response.

//The following notes will help to understand the code
//      Sets or retrieves the event handler for asynchronous requests.
//      See
//Note :req.readyState
//      Is an integer that receives one of the following values:
// 0:   The object has been created, but not initialized (the open method 
//      has not been called).
// 1:   A request has been opened, but the send method has not been called. 
// 2:   The send method has been called. No data is available yet. 
// 3:   Some data has been received; however, neither responseText 
//      nor responseBody is available. 
// 4:    All the data has been received. 
//Note :req.status
// 200: "OK"
// 404: Page not found
// When readyState=4 and status=200 the response is ready
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<link href="chatstyle.css" rel="stylesheet" type="text/css">
<title>Chat Room</title>
<body id="myContent" onLoad="doTimer()">
<div id="content"><h2>Chat Room</h2>
<div id="chatMessage">
//Set connection parameters
include ('open.php');

//make the connection
if (!$conn) 
    die("<h2><font color=#FF0000><blink>Error! :</blink></font>".mysql_error()."</h2>");

//select the database
//if database dows not exist an error message is displayed
@mysql_select_db($dbname) or die( "Unable to select database - named:  ".$dbname);

//Execute SQL
$query="SELECT * FROM messages";  
$result=mysql_query($query);  //The query result
$num=mysql_numrows($result);  //The number of rows returned by the query

//Output Message table content
//this outputs last message first
//and is limited to the last $n messages
$n=$num-10;  //show only ten most recent messages
while ($i > $n) 
    echo "<p>";
    echo '<b> '.$_SESSION['userid'].'  : </b>';
    echo '<i> '.mysql_result($result,$i,1).'</i>';
    echo "</table>";



<h3><a href="login.php">Enter</a> Your Message:</h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <br />
    <textarea  name="msg" class="code_input" rows="3" cols="55" wrap="logical"></textarea><br /><br />
    <input name="from" type="text"   size="30" maxlength="30" /> 
    <input name="Submit" type="submit" value="Send" /><br />

well this is a owl lot of codes. But I would give you a simple algorithm to do that. in the users table add a column called blockState (bool).


So you can set it to false by default. When you now want to block a user you set it to true. This means that before a users is allowed to chat you would check the block state column querying with the user_id
so if the blockState column is true. You would inform the user that he or she as been blocked. if false allow the user to chat.
The on your admin side you would create a form that allows you to use the username to set the block to true for users you want to block and false for users you want to unblock.

I hope this little explanation would help.

Member Avatar

Thanks, Im suppsoed to be able to block people too

Er, this would be coursework I take it?

Yea, a basic chat with admin and users.

Member Avatar

Perhaps your chat app should just show the comments from the time that the user joins the conversation (like irc). So, your users will have a timestamp when they join the conversation and only comments from then on will appear in the user's window. Also, msgs should be in order oldest->newest (usual display anyway)

Your SQL for messages will need to show an INNER JOIN for displaying purposes. Here's an example

SELECT u.username, m.timestamp, m.msg FROM users AS u INNER JOIN messages AS m ON u.user_id = m.user_id WHERE m.timestamp > $jointime

You may want to add an order by and/or limit clauses to the above

Your messages in the data resource should now have the username, time of posting, message body. The time of posting may by in Y-m-d H:i:s or unix timestamp format. Other formats may give problems. I suggest that you only show the time part of the datetime/timestamp in the app.

add one field in message table to store the user id and at the time of retriving data compare the user id which comes from session to stored usre id and display only those messages

Member Avatar

I'd also suggest a clean-up with something like cron-job which you can set to run say, every night when traffic is low. This could run a DELETE query to get rid of the messages from the previous day(s). That should ensure that your messages table doesn't become ridiculously long with msgs.

Diafol, could you take a look at the link i posted previously ? login jessica pswd 1234, and have you any idea why its displaying twice ? I tried using ajax to update a particular div ever few seconds ?

jessicam your URL is incorrect...Please check if you are providing correct URL

Yea I know, had the messages showing yesterday, but they are not showing now. urltofetch is supposed to overcome caching at the browser.

I have the messages working, just need them to go in a different order, but no ajax. ?

How would I output the most recent message first ?

//Execute SQL
$query="SELECT *FROM `messages";  
<div id="myContent"> Dynamic content here 
while ($i > $n) 
    echo "<p>";
    echo '<b>'.$_SESSION['userid'].'  : </b>';
    echo '<i> '.mysql_result($result,$i,1).'</i>';
    echo "</table>";

Use order by descending for ID clause to get recent mesage

   $query="SELECT * FROM messages ORDER BY id DESC";

when I try that the new message doesnt show up at all ?

i am not sure about your table structure. Here id means autoincrement field in your table,i hope you have one?.

yes, I have id_msg as an auto increment.$query="SELECT *FROMmessagesORDER BYmessages.id_msgDESC";
I used this code and it doensnt show any new messages sent

i think so, it can be spacing problem.

$query="SELECT * FROM messages ORDER BY id_msg DESC";

You can check first "SELECT * FROM messages ORDER BY id_msg DESC" in your MySQL and then in your php chat app

It works in a query window but not on the app itself. Is it beacuse of this piece of code ?

$n=$num-12;  //show only ten most recent messages
while ($i > $n) 

don't use this if you want to show only 10 or 15 results.
You can use LIMIT clause

$query="SELECT * FROM messages ORDER BY id_msg DESC LIMIT 10";

Quote from

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

If you are not using pagination script,then you can use this.It will be better.

Member Avatar

Also it's mysql_num_rows not mysql_numrows

You need to pay attention to your spacing (as previously mentioned) and spelling of functions. These will trip you up even if your algorithm is sound.

Ajax is asynchronous - so some issues may come from this if you're running a few at a time. Check that you nest calls if you need one to finish before running the next

Also, libraries can be useful, such as jQuery. Dealing with ActiveX objects is horrible :( But, there again, your brief may insist on vanilla js, I don't know.

Ok, I got the messages to appear at the bottom. Thank you all, much appreciated. I also got the ajax working, so it does not show its self twice in the window. Now just on to the admin stuff, or maybe not.
Thank you all again.

To output the most recent message first you can use the order by class in your select statement.

select * from message order by msg_id desc;

This query would show content of the message table start from the recently entered messages before displaying the previously entered messages. Hope this would help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.