每当我想插入时查询失败

时间:2016-08-13 06:33:14

标签: php sql insert

每次我通过下面的代码提交表单时,我都会收到“查询失败”,但我似乎无法找到错误

  

您的SQL语法中有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'order(pass,phone,fname,lname)   VALUES('test@yahoo.com','060606060606','James''在第1行

请有人帮帮我。

<?php
//Start session
session_start();

//Include database connection details
require_once('../db/config.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

//Sanitize the POST values
$pass = clean($_POST['pass']);
$phone = clean($_POST['phone']);
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);

//Create INSERT query
$qry = "INSERT INTO order (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    header("location: success.php");
    exit();
}else {
    die("Query failed");
}
?>

我还试图检查用户输入是否为空且没有问题但是没有插入。

2 个答案:

答案 0 :(得分:3)

  

名称&#39;命令&#39;是MySQL保留的关键字。

使用反引号括起表名

$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";

                      ^ enlcose table name with backtick

<强> BACKTICK

enter image description here

答案 1 :(得分:0)

使用&#34; mysqli&#34;

$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = mysqli_query($conn,$qry);