我的SQL语法有错误? MySQLi麻烦

时间:2014-02-27 07:08:28

标签: php mysql sql mysqli

所以我有一些mysqli麻烦与错误的语法和东西相关。这是我的代码:

$username = $_COOKIE['asdf']; 
$link = mysqli_connect("localhost", "root", "<my password>", "blog");
$user = mysqli_real_escape_string($link, $username);
$cat = mysqli_real_escape_string($link, $_POST['category']);
$title = mysqli_real_escape_string($link, $_POST['title']);
$post = mysqli_real_escape_string($link, $_POST['post']);
$time = mysqli_real_escape_string($link, time());

        if(!empty($_POST)) {
        if(mysqli_query($link, "INSERT INTO posts (user,catid,title,post,date), VALUES ('$user', '$cat', '$title', '$post', '$time')"))
        echo 'Post successful!';
        else
        echo 'Error: ', mysqli_error($link);
        }

所有我打算做的是为一个简单的小博客制作一个简单的mysqli帖子创建脚本我正在测试和提高我的php / sql技能(我在这个东西是一个极端的菜鸟)但是当我尝试和使用脚本创建一个帖子我刚刚将它打印出来:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' VALUES ('<Username>', 'Test Post', 'dfgdfsd', 'sdfsd', '1393484072')' at line 1

我尝试删除每个变量的引号,并改为执行sqli查询:

if(mysqli_query($link, "INSERT INTO posts (user,catid,title,post,date), VALUES (%s,%s,%s,%s,%s)", $user, $cat, $title, $post, $time))

但要么没有改变任何东西,要么抛出关于“mysqli期待最多2个参数”或类似的随机错误。我真的不知道我哪里出错了 - 我会非常感激帮助,因为我在谷歌或这里找不到任何东西。谢谢!

6 个答案:

答案 0 :(得分:0)

删除列名后面的逗号。您的查询应该是:

"INSERT INTO posts (user,catid,title,post,date) VALUES ('$user', '$cat', '$title', '$post', '$time')"))

答案 1 :(得分:0)

您的SQL中还有一个,

INSERT INTO posts (user,catid,title,post,date) VALUES ('$user', '$cat', '$title', '$post', '$time')

此外,如果catid不是字符串数据类型(例如VARCHAR,TEXT等),则不需要单引号。

答案 2 :(得分:0)

您的查询中有额外的,
试试这个:

if(mysqli_query($link, "INSERT INTO posts (user,catid,title,post,date) 
 VALUES ('$user', '$cat', '$title', '$post', '$time')")
 )

答案 3 :(得分:0)

尝试此操作,在,之前删除VALUES,并为date列包含反引号(保留字)

INSERT INTO posts (user,catid,title,post,`date`) VALUES

而不是

INSERT INTO posts (user,catid,title,post,date), VALUES

答案 4 :(得分:0)

您的一个列名可能是mysql的关键字。 你应该用这个:

"INSERT INTO posts (`user`,`catid`,`title`,`post`,`date`) VALUES ('$user', '$cat', '$title', '$post', '$time')"

答案 5 :(得分:0)

以这种方式尝试第二块,

if(!empty($_POST)) {

   /* Prepared statement, stage 1: prepare */
   if (!($stmt = $link->prepare("INSERT INTO posts(user,catid,title,post,date), VALUES (?, ?, ? , ? , ?)"))) {
       echo "Prepare failed: (" . $link->errno . ") " . $link->error;
   }

   /* Prepared statement, stage 2: bind and execute */
   if (!$stmt->bind_param("sssss", $user, $cat, $title, $post, $time) ) {
      echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
   }

   if (!$stmt->execute()) {
      echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
   }
}