PHP Create a Shoutbox using MySQL
Make a shoutbox (mini forum) using MYSQL
database. Now to make your very own PHP shoutbox, which , first of all we need
to create a .html file which has a form for accepting user name and message with
a submit button, another .php file will connect to the database and insert the
values into the proper table, simultaneously it will fetch last five records
from the table and will display. But before that we need to create a table which
will store the name of the user and the message along with the time.
To create the table, first of all open the MySQL console or phpMyAdmin, then
open any database, (to display the list of databases type show databases;) .
type use database-name; after specifying any valid database name, MySQL will
activate the database, now to create the table for storing all the details of
user name, messages etc. type the following code:
CREATE TABLE ShoutBox (
`user-id` int(11) NOT NULL auto_increment,
`user-name` text NOT NULL,
`message` longtext NOT NULL,
`time` text NOT NULL,
PRIMARY KEY (`user-id`)
) engine="innodb";
After successfully creation of the table write the following code:
shoutBox.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My ShoutBox</title>
</head>
<body>
<form action="shoutBox.php" method="post" >
Name:
<input type="text" name="name" size=30 maxlength='100'></input><br/>
Message:
<input type="text" name="message" size=30 maxlength='100'></input><br/>
<input type="submit" name="submit" value="submit"></input>
</form>
</body>
</html>
shoutBox.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("roseindia");
$name=$_POST['name'];
$message=$_POST['message'];
$time=date("h:ia d/j/y");
$result=MYSQL_QUERY("INSERT INTO shoutbox (id,name,message,time)".
"VALUES ('NULL','$name', '$message','$time')");
$result = mysql_query("select * from shoutbox order by id desc limit 5"); 0
while($r=mysql_fetch_array($result))
{
$time=$r["time"]; 1
$id=$r["id"];
$message=$r["message"];
$name=$r["name"]; 2
echo $name."<br/>".$message."<br/>".$time."<br/>";
}
?> 3
Output:
4
After clicking 5 times submit button or refresh ( f5 ) button, the output will be as follows:
rosindia
this is new text
11:07am 11/11/09
rosindia
this is new text
11:03am 11/11/09
rosindia
this is new text
11:03am 11/11/09
rosindia
this is new text
11:03am 11/11/09
rosindia
this is new text
11:03am 11/11/09