简体   繁体   English

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

[英]how to insert form data into a mysql database

I'm trying to insert the data that's in the form into the database that I made. 我正在尝试将表格中的数据插入我创建的数据库中。 I keep getting this error when I check if the data is in the database: 当我检查数据是否在数据库中时,我不断收到此错误:

Error Code: 1064. You have an error in your SQL syntax; 错误代码:1064。 check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_comments' at line 1 检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行的“ user_comments”附近使用

This is my php: 这是我的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.";
}

?>

This is my html: 这是我的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>

As pervious people have commented you should construct your "query" separately, makes it easier to handle and change. 就像以前的人们评论过的那样,您应该分别构造“查询”,以使其更易于处理和更改。 Additionally when passing any variable into your query you need to bring them out of the string so PHP can process them correctly. 此外,将任何变量传递到查询中时,您需要将其从字符串中删除,以便PHP可以正确处理它们。

Here is how I would suggest you structure your code: 这是我建议您构建代码的方式:

.... ....

$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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM