duanshan1856 2013-12-20 21:35
浏览 41
已采纳

php mysql查询加入两个表

I've spent a long time today looking through SO and have yet to find an answer that I've implemented that works as I need and as this is the first time I've tried to join tables rather than create inefficient monsters, I thought I'd ask for help!

I have two tables:

  1. userData (id, surname, email)
  2. appointmentData (id, uid, appointmentNum, appointmentDate)

The uid in the second table corresponds with the id of the first table.

What I would like to do is display a table:

surname | email | appointment1 | appointment1 date | appointment2 | appointment2 date etc...

I tried:

mysql_query("SELECT * FROM userData as table1 INNER JOIN appointmentData as table2 ON table1.id = table2.uid ORDER BY table1.surname ASC");

But this will only display the first appointment for that particular user, if I use a while loop (I think I'm trying to display the data horizontally in the table when it's vertically in the array, if that makes sense):

while($row = mysql_fetch_array($result)) {
echo"<td>".$row['surname']."</td>";
echo"<td>".$row['email']."</td>";
echo"<td>".$row['apptDate']."</td>";
...
}

I'd really appreciate if someone could help point me in the right direction!

  • 写回答

5条回答 默认 最新

  • dongqishou7471 2013-12-20 21:46
    关注

    you can start with:

    $prevId = '';
    while($row = mysql_fetch_array($result)) {
        if ($row['id'] != $prevId) {
            if ($prevId != '') echo '</tr>'; // close previous row
            echo '<tr><td>' . htmlspecialchars($row['surname']) . '</td>';
            echo '<td>' . htmlspecialchars($row['email']) . '</td>';
            $prevId = $row['id'];
        }
        echo '<td>' . $row['apptDate'] . '</td>';
    }
    if ($prevId != '') echo '</tr>'; // close last row
    

    this will display table you needed, but table layout will not be very correct (browser will display properly, but actual html code will not be right)

    to fix this - you need to count how many columns were displayed and add appropriate number of empty <td></td> before closing </tr>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)