错误:第1行INSERT INTO的SQL语法出错

时间:2014-07-18 16:54:42

标签: php mysql mysqli

我试图在表格中插入一行。好吧,页面添加了行,但是当它出现时,会出现MySQL错误,如下所示:

  

错误:您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近' 1'在第1行

这是我的PHP代码:

<?php
$lang = "english";
header('Content-Type: text/html; charset=UTF-8');
require '../security.php';
$con=mysqli_connect($sec[0],$sec[1],$sec[2],$lang);
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$con->set_charset("utf8")) {
} else {
}

$result = mysqli_query($con,"INSERT INTO `ta_exp` (`date`, `cargo`, `DP`, `LP`, `url`)
VALUES ('".mysqli_real_escape_string($con,$_GET['date_exp'])."','".mysqli_real_escape_string($con,$_GET['cargo_exp'])."','".mysqli_real_escape_string($con,$_GET['lp_exp'])."','".mysqli_real_escape_string($con,$_GET['dp_exp'])."','".mysqli_real_escape_string($con,$_GET['url'])."')");

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

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:1)

mysqli_prepare是要走的路:

$query = "INSERT INTO `ta_exp` (`date`, `cargo`, `DP`, `LP`, `url`)
          VALUES (?, ?, ?, ?, ?)";          
if ($stmt = mysqli_prepare($con, $query)) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "sssss", $_GET['date_exp'],
                                           $_GET['cargo_exp'],
                                           $_GET['lp_exp'],
                                           $_GET['dp_exp'],
                                           $_GET['url']);

    /* execute query */
    mysqli_stmt_execute($stmt);
}

答案 1 :(得分:0)

最后我的代码看起来像这样:

$con = new mysqli($sec[0],$sec[1],$sec[2],$lang);
if ($con->connect_error) {
  trigger_error('Database connection failed: '  . $con->connect_error, E_USER_ERROR);
}
if (!$con->set_charset("utf8")) {
} else {
}
$sql = "INSERT INTO experiences (`date`, `cargo`, `DP`, `LP`, `url`)
VALUES ('".mysqli_real_escape_string($con,$_GET['date_exp'])."','".mysqli_real_escape_string($con,$_GET['cargo_exp'])."','".mysqli_real_escape_string($con,$_GET['lp_exp'])."','".mysqli_real_escape_string($con,$_GET['dp_exp'])."','".mysqli_real_escape_string($con,$_GET['url'])."')";

if($con->query($sql) === false)
{
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
} else {
  $last = $con->insert_id;
  $aff = $con->affected_rows;
}

$con->close();