2
我正在一個簡單的聊天頁面上,用戶寫他的名字和他的消息,並點擊一個提交按鈕,將他重定向到相同的表單頁,現在他可以看到他消息就在表單下面,注意消息按最新排序。不能添加新的元素到我的表
我的問題是,當我例如在我的頁面上寫一個名稱和一條消息,然後單擊發送沒有出現,並且沒有添加到我的表中。但是,當我手動(從phpmyadmin)出現消息。
我認爲我的sql查詢有問題,但我無法找到它,我知道尋求你的幫助,告訴我什麼是錯的,以及如何糾正它。
我的代碼分爲兩個文件:chat.php和chat_post.php。
chat.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mini chat</title>
<style>
body{
background-color: grey;
}
div#f, p{
text-align: center;
font-weight: bold;
}
input#mbox{
height: 300px;
width: 200px;
}
</style>
</head>
<body>
<p>Bienvenue à la page de chat</p>
<div id="f">
<form method="POST" action="chat_post.php">
pseudo : <br>
<input type="text" name="pseudo" ><br><br>
message : <br>
<input type="text" name="message" id="mbox" ><br><br>
<input type="submit" value="envoyer">
</form>
</div>
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=learn','root','');
}
catch(Exception $e){
die('Erreur : '.$e->getMessage());
}
$a=$db->query('SELECT pseudo,message FROM chat ORDER BY id DESC LIMIT 0,10');
while ($b=$a->fetch()) {
echo '<p>'.htmlspecialchars($b['pseudo']).' : '.htmlspecialchars($b['message']).'</p>';
}
$a->closeCursor();
?>
</body>
</html>
chat_post.php:
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=learn','root','');
}
catch(Exception $e){
die('Erreur : '.$e->getMessage());
}
if (isset($_POST['pseudo']) && isset($_POST['message'])) {
$a = $db->prepare('INSERT INTO chat(id,pseudo,message) VALUES(pseudo,message)');
$a ->execute(array('pseudo' =>$_POST['pseudo'],'message' => $_POST['message']));
header('Location : chat.php');
echo "message added";
}
?>
在此先感謝
'INSERT INTO chat(id,pseudo,message)VALUES(pseudo,message)'仔細看看這個。 (1,2,3) - (1,2)。如果你檢查了錯誤,它會引發你一些關於它的事情。 –
'header('Location:'這是另一個錯誤。「位置」和冒號之間不應有空格。 –
@ Fred-ii-這個id是自動遞增的,所以我應該寫什麼而不是什麼? – Blueberry