2014-09-13 39 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注入。無論出於何種原因,就是這樣。