2011-11-23 55 views
0

這是原來的MySQL查詢:MySQL查詢添加到PHP文件

UPDATE jos_bully_table AS jbt1 
INNER 
    JOIN (SELECT jbt2.bully_concat_name, 
       COUNT(*) AS b_name_count 
      FROM jos_bully_table AS jbt2 
      GROUP 
      BY jbt2.bully_concat_name 
     ) AS jbt3 
    ON jbt3.bully_concat_name = jbt1.bully_concat_name 
    SET jbt1.b_name_count = jbt3.b_name_count 
; 

它從phpMyAdmin的運行時的偉大工程。我點擊創建PHP代碼,這會產生:

$sql = "UPDATE jos_bully_table AS jbt1\n" 
    . " INNER\n" 
    . " JOIN (SELECT jbt2.bully_concat_name,\n" 
    . " COUNT(*) AS b_name_count\n" 
    . " FROM jos_bully_table AS jbt2\n" 
    . " GROUP\n" 
    . " BY jbt2.bully_concat_name\n" 
    . ") AS jbt3\n" 
    . " ON jbt3.bully_concat_name = jbt1.bully_concat_name\n" 
    . " SET jbt1.b_name_count = jbt3.b_name_count\n" 
    . ""; 

我試圖運行從一個php文件相同的查詢,但是該數據庫沒有更新。

這裏是我的PHP文件:

<?php 

$database = "xxxxxxxxx" ; 
$username = "xxxxxxxxx" ; 
$password = "xxxxxxxxx" ; 

mysql_connect(localhost,$username,$password); 
@mysql_select_db($database) or die("Unable to select database"); 


mysql_query($sql); 

$sql = "UPDATE jos_bully_table AS jbt1\n" 
    . " INNER\n" 
    . " JOIN (SELECT jbt2.bully_concat_name,\n" 
    . " COUNT(*) AS b_name_count\n" 
    . " FROM jos_bully_table AS jbt2\n" 
    . " GROUP\n" 
    . " BY jbt2.bully_concat_name\n" 
    . ") AS jbt3\n" 
    . " ON jbt3.bully_concat_name = jbt1.bully_concat_name\n" 
    . " SET jbt1.b_name_count = jbt3.b_name_count\n" 
    . ""; 

echo "<!-- SQL Error ".mysql_error()." -->"; 

?> 

有什麼不對呢?

回答

5

您正在運行您的查詢字符串之前,您已定義它。

$sql = "SELECT ..." 
$result = mysql_query($sql) or die(mysql_error()); 

同樣,考慮HEREDOC S代表限定多行字符串:

$sql = <<<EOL 
SELECT .. 
FROM ... 
WHERE ... 
ORDER BY .. 
EOL; 

比多行級聯更加可讀