2017-05-28 163 views
1

我設計了一個簡單的關係數據庫。當我試圖從它拋出一個錯誤的服務器中的數據:(我跳過了一些代碼,使其簡單)使用PHP從關係數據庫獲取數據時出錯

這是我使用的SQL語法:

$sql = "SELECT lead.id, lead.name, lead.phone, lead.email, treatment.name, source.name, status.name FROM lead join treatment join source join status on treatment.id = lead.treatment_id and source.id = lead.source_id and status.id = lead.status_id"; 

這是

echo " 
 
<tr> 
 
<td>".$row["lead.id"]."</td> 
 
<td>".$row["lead.name"]."</td> 
 
<td>".$row["lead.email"]."</td> 
 
<td>".$row["treatment.name"]."</td> 
 
<td>".$row["source.name"]."</td> 
 
<td>".$row["status.name"]."</td> 
 
</tr>";

此代碼是給了一個錯誤,當我改變$row["lead.id"] to $row["id"]它的工作原理,但我需要:HTML裏面使用提到表名,因爲我幾乎在所有表中都有相同的列名。

有沒有辦法使用表名來做到這一點?

回答

1

您有在錯誤的地方,並用不正確的,條件 條件,你應該在條件爲每個表使用

$sql = "SELECT 
      lead.id 
     , lead.name 
     , lead.phone 
     , lead.email 
     , treatment.name 
     , source.name 
     , status.name 
     FROM lead 
     join treatment on treatment.id = lead.treatment_id 
     join source on source.id = lead.source_id 
     join status on status.id = lead.status_id"; 

和索引嘗試使用別名 避免表名和點符號

$sql = "SELECT 
      lead.id as lead_id 
      , lead.name as lead_name 
      , lead.phone as lead_phone 
      , lead.email as lead_email 
      , treatment.name as treatment_name_ 
      , source.name as source_name 
      , status.name as status_name 
     FROM lead 
     join treatment on treatment.id = lead.treatment_id 
     join source on source.id = lead.source_id 
     join status on status.id = lead.status_id"; 
+0

我已經嘗試過你的解決方案,但是當我使用這個'$ row [「lead.id」]' – Jayprakash

+0

@Jayprakash時,它仍然會說'Undefined index:lead.id'。 ia已經用建議更新了答案 – scaisEdge

+0

你太棒了!有效。謝謝 – Jayprakash