PHP从数据库中检索数据并在文本区域中显示

时间:2015-07-16 23:55:00

标签: php

我试图在先前创建的文本区域中显示来自数据库的检索数据。代码应该是用户获取昵称和输入消息,将其存储在数据库中并将其检索回文本区域,类似于单人聊天(单击“发送消息”后输入的内容应存储到数据库中并检索并显示在文字区)。我能够存储到我的数据库中并在文本区域外的任何地方显示检索到的数据。任何帮助赞赏。谢谢!

代码:

<!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>

更新:

<?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>

1 个答案:

答案 0 :(得分:0)

对于您的表单,我建议如下:

<?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>

然后在你的Post处理程序中,执行以下操作:

<?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");
?>

进一步说,您可以通过JS添加TimeStamps,您可以使用AJAX发布数据而不是使用表单。只需删除重定向和会话数据即可。此外,如果用户意外关闭浏览器并返回,则如果会话仍处于活动状态,则应重新填充数据。

还可以编译聊天并每分钟左右将其自动保存到数据库中,而不是每次聊天操作。添加一个离开按钮可以终止会话并在那时将所有内容保存到数据库中。有很多方法可以做到。

上面的代码未经测试。

评论后编辑

对于您的聊天页面,我建议将textarea更改为div,以便更好地控制样式。以下是样式的示例: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>

您的Post处理程序也有一些更改(不应包含在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");
?>

如果是我,我会改进我的数据库架构。该表可以包含更多列:ID, DateStamp, Sender, Recipient, Message。希望这有助于,再次,未经测试。