I'm a newbie in php and I'm playing around trying to write a mini chat web app. Here is my code: a page for connecting to the database are retrieving all informations have been posted preceedingly.
<?php
try{
$bdd = new PDO('mysql:host=localhost;dbname=chat', 'root', '');
}
catch(Exception $e)
{
die('Error: ' . $e->getMessage());
}
$myname =$_POST["myname"];
$message =$_POST["message"];
$req = $bdd->prepare('INSERT INTO users(myname, message) VALUES(
:myname,
:message)');
$req->execute(array(
'myname' => $myname,
'message' => $message,
));
include('page1.php');
$reponse = $bdd->query('SELECT myname, message FROM users ORDER
BY ID DESC');
while ($mydata = $reponse->fetch())
{
echo '<p>' .($mydata['myname']) .
'</strong> : ' . ($mydata['message']) . '</p>';
}
?>
Another page which contain my form where users come and post their messages
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<title>chat</title>
</head>
<body>
<fieldset width="90">
<marquee>my mini chat </marquee>
<form method="post" action="enregisteur.php">
<label for="Identifier"> Identifier :</label>
<input type="text" name="myname" id="myname" value="myname" placeholder="myname"/>
<br>
<label for="message"> Messages :</label>
<textarea name="message" id="message" value="message">
</textarea>
<br>
<input type="submit" name="validate" value=" validate " size="15"/>
</form>
</fieldset>
</body>
</html>
This works well but there is a little issue that I want to get ripe of: I a user say user1 comes and enter user1 and the messages Hello and then clicks on submit. The information goes to the database and it is displayed on the web page. If he there goes ahead and do a reload of the page without clicking on submit the same information is sent to the database and displayed again on the web play. That is we would have something like this on the web page
After clicking on submit user1: Hello After reloading the page user1: Hello user1: Hello
This happen after every reload
Please any help will be welcoming. Thanks.
separate your insert and select query to different pages:
create a new page and move your insert query:
<?php
try{
$bdd = new PDO('mysql:host=localhost;dbname=chat', 'root', '');
}
catch(Exception $e)
{
die('Error: ' . $e->getMessage());
}
$myname =$_POST["myname"];
$message =$_POST["message"];
$req = $bdd->prepare('INSERT INTO users(myname, message) VALUES(
:myname,
:message)');
$req->execute(array(
'myname' => $myname,
'message' => $message,
));
header('location:enregisteur.php');
?>
And change your form action to new page