Reputation: 13
I m trying to display retrieved data from the database in the earlier created text area. Code is supposed to get users nickname and input message, store both in database and retrieve it back to text area, smth similar to one man chat (whatever is typed after clicking 'Send message' should be stored to database and retrieved and shown in the text area). I am able to store into my database and display retrieved data anywhere outside the text area. Any help appreciated. Thank you!
Code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<center>
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</form>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
$query = mysql_query('select * from messages');
while ($entry = mysql_fetch_object($query))
{
printf("<p>%s <br />- <em>%s</em></p>",
htmlentities($entry->message),
htmlentities($entry->nickname)
);
}
?>
</body>
</html>
postmessage.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<?php
$nickname=$_POST['nickname'];
$message = $_POST['message'];
$nickname = mysql_real_escape_string($nickname);
$message = mysql_real_escape_string($message);
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
if (!mysql_query(
"insert into messages (nickname, message) VALUES ('$nickname', '$message')"
)){
echo ("Could not process your send request");
};
?>
<body>
</body>
</html>
UPDATED:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage1.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }?></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
post..php:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
</body>
</html>
Upvotes: 1
Views: 12647
Reputation: 30883
For your form, I suggest the following:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }</textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
Then in your Post handler, do this:
<?php
start_session();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickName'] = htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
Taking this further, you can add TimeStamps via JS and you can use AJAX to post the data instead of using the form. Just drop the redirects and the session data. Also if the user closes the browser by accident, and returns, it should re-populate the data if the session is still alive.
Could also compile the chat and autosave it into DB every min or so instead of every chat action. Adding a leave button can kill the session and save everything to the DB at that time. Lots of ways to do it.
Code above is untested.
EDIT after comments
For your Chat page, I suggest changing the textarea
to a div
for better style control. Here is an example of the style: http://jsfiddle.net/Twisty/8frqcyyk/
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
.chatForm {
background: #ccc;
border: 1px solid #000;
width: 40em;
}
.chatForm ul {
padding: 0;
width: 30em;
margin: 5px auto;
}
.chatForm ul li {
list-style: none;
}
.chatForm ul li label {
display: block;
font: 1em Verdana, sans-serif;
}
.chatForm label.title {
background: #222;
border: 3px solid #222;
color: #FFF;
display: block;
font: 1em Verdana, sans-serif;
height: 1.5em;
margin: 0px auto;
width: 30em;
}
.center {
text-align: center;
}
.chatHistory {
background: #fff;
border: 1px inset #DDD;
display: block;
font: 1em Verdana, sans-serif;
height: 15em;
margin: 0px auto;
overflow-y: scroll;
padding: 2px;
text-align: left;
width: 30em;
}
.chatHistory p {
margin: 5px 0;
}
.chatHistory label {
display: inline-block;
font: bold 0.85em Arial, sans-serif;
width: 100px;
}
.chatHistory label.senderName {
color: blue;
}
.chatHistory label.nickName {
color: red;
}
.messageText {
width: 75%;
}
input[type='submit'] {
font: .85em Arial, sans-serif;
width: 20%;
}
</style>
</head>
<body>
<form method="post" action="postmessage.php">
<div class="chatForm">
<label for="output" class="center title">Chat History</label>
<div id="output" class="chatHistory">
<?php echo $_SESSION['currentChat']; ?>
</div>
<ul>
<li>
<label for="nickname">Nickname</label>
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
</li>
<li>
<label for="message">Type your message here:</label>
<input name="message" type="text" id="message" class="messageText" /><input type="submit" value="Send" /></li>
</ul>
</div>
</form>
</body>
</html>
A few changes for your Post handler too (that should not be wrapped in HTML):
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$results = $mysqli->query("SELECT * FROM messages");
$updateChat = "";
while($row = $results->fetch_assoc()){
$updateChat .= "<p><label>". htmlentities($row['nickname'] .":</label>";
$updateChat .= htmlentities($row['message']) . "</p>\r\n";
}
$results->free();
$mysqli->close();
$_SESSION['currentChat'] = $updateChat;
// Redirect back to display content
header("Location: chatform.php");
?>
If it were me, I would improve me DB schema. The table could include more columns: ID, DateStamp, Sender, Recipient, Message
. Hope that helps, and again, untested.
Upvotes: 1