php - 通过PHP在MySQL中插入元素我得到语法错误

标签 php mysql sql syntax-error sql-insert

这是错误的:

INSERT INTO registration_table(username,password,email,phonenum)VALUES
('rahul','hdhh','rahul@gmail.com','7386627473')

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'name,password,email,phonenum)VALUES ('rahul','hdhh','rahul@gmail.com','738662747' at line 1`


<html>  
    <body>  
        <?php
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $user_name = $_POST["uname"];
            $password = $_POST["password"];
            $email = $_POST["email"];
            $phonenum = $_POST["phno"];
        }
        $link = mysqli_connect('localhost', 'root', '', 'test_ybf');
        if (!$link) {
            die('Could not connect: ' . mysqli_connect_error());
        }

        $sql = "INSERT INTO registration_table(user name,password,email,phonenum)VALUES ('$user_name','$password','$email','$phonenum')";
        if (mysqli_query($link, $sql)) {
            echo "success";
        } else {
            echo "error:" . $sql . "<br>" . mysqli_error($link);
        }
        mysqli_close($link);
        ?>  
    </body>  
</html>

最佳答案

MySQL中的列通常不能在其中包含空格。如果user name不只是一个错字,则应使用反引号将其转义:

$sql="INSERT INTO registration_table(`user name`,password,email,phonenum)VALUES ('$user_name','$password','$email','$phonenum')";  
# Here-------------------------------^---------^

强制性评论:
在SQL语句中使用字符串替换使您的代码容易受到SQL Injection攻击。您应该真正研究prepared statements

关于php - 通过PHP在MySQL中插入元素我得到语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452841/

相关文章:

sql - 如何有效地对复杂 SQL 查询的结果进行分页?

mysql - 如何在基于 startTime 的单个 SQL 查询中添加和减去

php - 如何使用group_by codeIgniter根据id从数据库中求和数据

mysql - 如何为每个注册的新用户启动自动增量

PHP选择多个数组表

mysql - 如何获取 MySQL 中逗号分隔字段的最大值?

mysql - 按天计算答案 mySQL

mysql - 如何在 mysql 中的 varchar 中执行 SQL 插入

php - Woocommerce - 如何根据支付类型发送自定义电子邮件

php - 使用 PHP 和 MySQL 仅显示当前用户的详细信息