使用PHP

时间:2017-05-28 19:02:23

标签: php mysql

我设计了一个简单的关系数据库。当我试图从服务器获取数据时,它会抛出一个错误:(我已跳过一些代码使其变得简单)

这是我正在使用的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";

这在HTML中使用:

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"]时,我需要提及表名,因为我几乎在所有表中都有相同的列名。

有没有办法使用表名来做?

1 个答案:

答案 0 :(得分: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";