1

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>
3
  • Can you post the code where you're trying to show it in the textarea? Commented Jul 17, 2015 at 0:00
  • Welcome to Stack Overflow. You're going to get pounced on for using MySQL. It's deprecated and should not be used, suggest MySQLi or PDO. Commented Jul 17, 2015 at 0:02
  • Where is your textarea, last i see it was look like this <textarea name="textarea"></textarea> Commented Jul 17, 2015 at 0:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thnx a lot. I fixed some typos and stuff in your code (check updated code above) and now i am able to get messages in the text area , however messages do not go one below another and nickname (who sent the message) is missing. I've tried adding another echo to text area, but all nicknames go at the end of the messages. Earlier you had nickname pointing to Nickname text input, now deleted (should go to text area). Another thing i noticed, if i delete some messages from my database and refresh 'chatform' in my browser old messages are still showing although not present in my database.
So the Text Field and Text Area elements are raw text. If you want to wrap the text, you need to append a New Line on to the end: . "\r\n";. If this was me, I would use a DIV and wrap your content with specific class code so I can control them via CSS. The delete issue means you would want to re-populate the session data with a query from the DB before redirecting back. I will add an edit to show what I mean.
Great. I may have written it up quickly. If it helped you out, I hope you would like to mark it as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.