簡體   English   中英

查詢聯接同一表3次

[英]Query joining the same table 3 times

我創建了一個在phpMyAdmin中完美運行的查詢,但是當我嘗試在.php文件中調用它時,出現以下錯誤。

Undefined variable: mothers_name in C:\wamp\www\Family_Tree\showfamily.php on line 56

我的代碼是:

$select_query = "SELECT a.id, CONCAT( a.surname,  ', ', a.first_names ) AS child_name, " . 
"CONCAT( b.surname,  ', ', b.first_names ) AS mothers_name, " .
"CONCAT( c.surname, ', ', c.first_names ) AS fathers_name " .
"FROM family_members a " .
"INNER JOIN family_members b ON a.mother_id = b.id " .
"INNER JOIN family_members c ON a.father_id = c.id" .
"WHERE a.id = " . $user_id;

我收到此錯誤消息是因為在通過mysql_query($ select_query)函數調用SQL之前,表“ a”,“ b”和“ c”以及字段“ mother_id”和“ father_id”並不存在。

第56行之前的代碼將查找,返回並按原樣顯示結果。

..._id = c.id" .               // <-- you forgot a space, results in c.idWHERE
"WHERE a.id = " . $user_id;

如果您退出Java樣式的換行並進行攻擊,那么可能會發現這一切容易得多。 PHP無需對其進行拆分,並且額外的標點符號使錯誤更容易實現。

$select_query = 
"SELECT 
     a.id, 
     CONCAT( a.surname, ', ', a.first_names ) AS child_name, 
     CONCAT( b.surname, ', ', b.first_names ) AS mothers_name,
     CONCAT( c.surname, ', ', c.first_names ) AS fathers_name 
FROM family_members a 
INNER JOIN family_members b ON a.mother_id = b.id 
INNER JOIN family_members c ON a.father_id = c.id
WHERE a.id = " . $user_id;

這將使您使用非常方便的調試工具:

echo "[pre]" . $query . "[/pre]";

[&]實際上是<&>。 抱歉,SO新手。

然后,您將能夠將實際查詢從瀏覽器窗口復制/粘貼到phpMyAdmin中,然后運行該查詢,看看它們是否完全相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM