错误SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法中有错误

时间:2017-07-12 11:13:58

标签: php mysql sql

我有一个PHP代码,它从HTML表单中获取数据并插入到SQL表中。但我可以因为错误而这样做:

这是我的代码:

<html>
<?
    $name = $_get['name'] ;
    $mob = $_get['mob'] ;
    $email = $_get['email'] ;

    //config
    $servername = "localhost";
    $username = "lozaair_datam";
    $password = ".8#l2)S3+d%*";
    //end-config

    //db connect
    try {
        $conn = new PDO("mysql:host=$servername;dbname=lozaair_orders", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


        //data input

        $sql = "INSERT INTO `orders` (`name`, `mob`, `email`) VALUES ($name , $mob , $email )";

        $conn->exec($sql);
        //end- data input


        echo "New record created successfully"; 
    }
    catch(PDOException $e)
    {
        echo $sql . "<br>" . $e->getMessage();
    }
    //end- db connect

    //db close
        $conn = null;
    //end- db close
    ?>
</html>

我尝试了很多方法,但没有工作。

1 个答案:

答案 0 :(得分:1)

我认为您需要在查询中用单引号括起变量。尝试下面一个:

$sql = "INSERT INTO `orders`(`name`, `mob`, `email`) VALUES('$name', '$mob', '$email')";