gpt4 book ai didi

php - 如何将表单数据插入mysql数据库

转载 作者:行者123 更新时间:2023-11-29 13:09:15 25 4
gpt4 key购买 nike

我正在尝试将表单中的数据插入到我创建的数据库中。当我检查数据是否在数据库中时,我不断收到此错误:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_comments' at line 1

这是我的 php:

<?php
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}else{
echo "it worked";
}

if(isset($_POST['insertComments'])){
$name=$_POST['name'];
$comment=$_POST['comment'];
mysqli_query($db_connection,"INSERT INTO user_comments (name, comment) VALUES ($name, $comment)");
Print "Your information has been successfully added to the database.";
}

?>

这是我的 html:

<div id="uploadComments">
<form id="insertComments" name="insertComments" method="post">
<label for="name">Name: </label><input type="text" id="name" name="name"><br/>
<label for="comment">Comments: </label><textarea name="comment" id="comment"></textarea>
<input type="submit" value="Submit">
</form>
</div>

最佳答案

正如之前的人评论的那样,您应该单独构建“查询”,这样更容易处理和更改。此外,当将任何变量传递到查询中时,您需要将它们从字符串中取出,以便 PHP 可以正确处理它们。

以下是我建议您构建代码的方式:

...

$name=$_POST['name'];
$comment=$_POST['comment'];

$sql="INSERT INTO user_comments (name, comment)VALUES('{$name}','{$comment}')";

if (!mysqli_query($db_connection,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

关于php - 如何将表单数据插入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310615/

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