不能添加新的元素到我的表
问题描述:
我正在一个简单的聊天页面上,用户写他的名字和他的消息,并点击一个提交按钮,将他重定向到相同的表单页,现在他可以看到他消息就在表单下面,注意消息按最新排序。不能添加新的元素到我的表
我的问题是,当我例如在我的页面上写一个名称和一条消息,然后单击发送没有出现,并且没有添加到我的表中。但是,当我手动(从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)
缺少值和缺少冒号中的参数。
INSERT INTO chat(id,pseudo,message) VALUES('', :pseudo, :message)
或者,由Xorifelse
INSERT INTO chat(pseudo,message) VALUES(:pseudo, :message)
表示既会工作。
和Location
和冒号之间的额外空格需要删除。
header('Location : chat.php');
^right there
到
header('Location: chat.php');
exit;
参考:http://php.net/manual/en/function.header.php
取出回声也并添加一个出口,以防止进一步执行。
参考链接以检查错误:
- http://php.net/manual/en/pdo.error-handling.php
- http://php.net/manual/en/function.error-reporting.php
参考为PDO的准备语句:
'INSERT INTO chat(id,pseudo,message)VALUES(pseudo,message)'仔细看看这个。 (1,2,3) - (1,2)。如果你检查了错误,它会引发你一些关于它的事情。 –
'header('Location:'这是另一个错误。“位置”和冒号之间不应有空格。 –
@ Fred-ii-这个id是自动递增的,所以我应该写什么而不是什么? – Blueberry