gpt4 book ai didi

php - 无法向我的表中添加新元素

转载 作者:行者123 更新时间:2023-11-27 23:16:34 25 4
gpt4 key购买 nike

我正在开发一个简单的聊天页面,用户在其中写下他的名字和消息,然后单击提交按钮,将他重定向到同一个表单页面,现在他可以在表单下方看到他的消息,请注意消息按最新排序。

我的问题是,例如,当我在页面中写下姓名和消息并单击“发送”时,什么也没有出现,也没有任何内容添加到我的表格中。但是,当我手动(从 phpmyadmin )执行此操作时,会出现消息。

我认为我的 sql 查询有问题,但我没能找到它,我知道寻求您的帮助,告诉我哪里出了问题以及如何更正它。

我的代码分为两个文件:chat.php 和 chat_post.php。

聊天.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

也删除 echo 并为其添加一个导出以防止进一步执行。

检查错误的引用链接:

PDO 准备好的语句引用:

关于php - 无法向我的表中添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com