2014-09-13 43 views
1

我不同意。我的SQL查询只能通过PhpMyAdmin发送。如果我试图通过PHP发送这个特定的查询,我得到一个错误。当我将精确的查询复制到PhpMyAdmin时,它会毫无问题地完成。SQL错误只发生在PHP脚本中

INSERT INTO posts (id, content, poster, timestamp, tags) VALUES ('12056242', 'OMG I just got a #toyota', 'Clunker5', '09/12/14 08:43:36', 'toyota');INSERT INTO `tags` (tag, posts) VALUES ('toyota', 1) ON DUPLICATE KEY UPDATE posts=posts+1; UPDATE `tags` SET posts=posts+1 WHERE tag IN ('toyota'); 

这是与问题相关的

//Ups one post for all tags entered by the user 
    if(!empty($tags)){ 
     $tags1 = explode(",", $tags); 
     $tags_submit = join("','", $tags1); 
     $tags_insert = join("', 1), ('", $tags1); 
     $sql = "INSERT INTO posts (id, content, poster, timestamp, tags) VALUES ('$d', '$b', '".$_SESSION['username']."', '$c', '$tags');" 
       . "INSERT INTO `tags` (tag, posts) VALUES ('".$tags_insert."', 1) 
         ON DUPLICATE KEY UPDATE posts=posts+1; 
         UPDATE `tags` SET posts=posts+1 WHERE tag IN ('".$tags_submit."');"; 

    $result = mysql_query($sql); 
    }else{ 
     $sql = "INSERT INTO posts (id, content, poster, timestamp, tags) VALUES ('$d', '$b', '".$_SESSION['username']."', '$c', '$tags');"; 

    $result = mysql_query($sql); 
    } 
    $error = mysql_error(); 
    if($result){ 
     echo "1"; 
    }else{ 
     echo error($sql, $error, "Tags: ".$tags, "Post: ".$b, "ID: ".$d); 
    } 
PHP代码

的错误是

SQL Response: 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 'INSERT INTO `tags` (tag, posts) VALUES ('toyota', 1), ('ohmygoodness', 1) ' at line 1. 

编辑:现在,我知道,我不能做一个多查询,怎么能我做这个查询?

INSERT INTO `tags` (tag, posts) VALUES ('".$tags_insert."', 1) 
         ON DUPLICATE KEY UPDATE posts=posts+1; 
         UPDATE `tags` SET posts=posts+1 WHERE tag IN ('".$tags_submit."'); 
+1

你会得到什么错误?你在检查mysql_error()吗?插入变量后确定查询是否正确? – 2014-09-13 00:47:01

+1

今天第3个类似的问题。 – 2014-09-13 00:49:08

+0

INSERT INTO tags(tag,posts)VALUES('toyota',1),('ohmygoodness',1)' - 我从来没有见过像这样的VALUES条款,那该怎么办? – David 2014-09-13 00:56:44

回答

2

你正在试图做的多条语句在API函数的一次调用,但mysql_query()不支持多查询。

你不应该无论如何使用多查询。你可能会暴露于SQL injection vulnerabilties的全班。

你应该单独执行每个SQL语句,在mysql_query()单独调用。

此外,从@JohnConde的评论是恰当:你应该总是mysql_query()检查返回值,因为它返回,如果有一个错误。如果发生这种情况,请记录或报告mysql_error()以了解更多有关错误的信息。

0

今天我有同样的问题,我有2个伟大的答案。每次你有一个SQL语句你需要使用mysql_query;这是一个更好的说明,例如,如果你有

"INSERT INTO query"; 
"INSERT INTO 2nd query"; 
mysql_query(process both query "INSERT INTO query"; 
this isn't going to work, it'll only work in phpmyadmin or 
in straight mysql command line sql. not in a php script. 

you'll need to: 

"INSERT INTO query"; 
mysql_query(process one query); //you should also use mysql_error() to see the response 
"INSERT INTO 2nd query"; 
mysql_query(process 2nd query); 

它需要在2个独立的mysql查询中形成。其在PHP端的安全功能,以防止sql注入。无论出于何种原因,就是这样。