2011-05-07 72 views
1

我的sql查詢時,我手動檢查phpmyadmin工作正常,但是當我嘗試通過php mysql_query處理它時拋出一個語法錯誤。如何解決這個問題?SQL語法是好的,但PHP仍然拋出錯誤

錯誤消息:

Invalid query: 
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 scores(user_id) VALUES (LAST_INSERT_ID())' at line 1 
Whole query: 
INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login) 
VALUES ('1000001010101010', 'Bart Roza', 'Bart', 'Roza', '[email protected]','http://www.facebook.com/profile.php?id=1000001010101010','2011-05-07 11:15:24'); 
INSERT INTO scores(user_id) VALUES (LAST_INSERT_ID()); 

我的PHP函數:

public function createUser() 
{ 
    $time = date("Y-m-d H:i:s"); 

    $insert = "INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login) VALUES (" . 
       "'" . $this->me['id'] . "', " . 
       "'" . $this->me['name'] . "', " . 
       "'" . $this->me['first_name'] . "', " . 
       "'" . $this->me['last_name'] . "', " . 
       "'" . $this->me['email'] . "'," . 
       "'" . $this->me['link'] . "'," . 
       "'" . $time . "'); " . 
       "INSERT INTO scores(user_id) VALUES (LAST_INSERT_ID());"; 

    $result = mysql_query($insert); 
    if (!$result) { 
     $message = 'Invalid query: ' . mysql_error() . "\n"; 
     $message .= 'Whole query: ' . $insert; 
     die($message); 
    } 
} 

編輯:

感謝您的解決方案!

+2

如果遇到mySQL查詢問題,請始終查看最終生成的查詢,而不是PHP代碼。 PHP代碼在這裏毫無意義 – 2011-05-07 09:47:59

+1

@Pekka:在這種情況下 - 它是有意義的。 – zerkms 2011-05-07 09:49:07

回答

5

由於mysql_query只接受一個查詢,因此需要將查詢字符串拆分爲2個分隔的查詢,並使用2個mysql_query調用執行查詢。

2

您不能使用mysql_query函數一次運行多個查詢。你必須有獨立mysql_query調用運行這兩個查詢

的mysql_query()發送一個唯一的查詢 (多個查詢不支持)

0

AS @zerkms和@Shakti說,請求mysql_query不支持多個查詢。如果你想使用這種功能,考慮遷移到mysqli。它支持單個數據包中的多個查詢mysqli_multi_query