在其他SE成员的帮助下,我创建了一个简单的聊天,用户添加了他/她的昵称和消息,但是我现在拥有它的方式只显示没有昵称的消息(代码的一部分)删除昵称的地方)。尝试了多个解决方案(比如向textarea添加另一个echo会话),但昵称最终一起结束并与消息分开。像这样的Smth:
message 1
message 2
JohnDave
而不是
John - message 1
Dave - message 2
或任何类似的变体(消息下面的昵称......)
非常感谢任何帮助。
chatform.php
<?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']."\n";}?></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>
postmessage1.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. "\r\n");
// Redirect back to display content
header("Location: chatform.php");
?>
</body>
</html>