You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP操作MySQL时如何JOIN关联两表输出客户姓名字段

修改方法

你只需要调整三处代码即可实现关联clients表展示所有者姓名的需求:

  • 替换原SQL查询语句,使用LEFT JOIN关联两张表,指定查询字段避免表字段重名冲突,使用左连接可以保证未绑定客户的机器数据不会被过滤掉
  • 修改表头,将原来展示「Client ID」的列名改为客户名称对应列名
  • 调整结果循环逻辑,读取关联查询得到的full_name字段输出,替换原来的client_id输出

修改后完整核心代码

<table class="tbl-full" id="clients">
        <tr>
            <th>ID</th>
            <th>VIN</th>
            <th>Model</th>
            <!-- 替换原Client ID表头 -->
            <th>客户姓名</th>
            <th>Desc</th>
            <th>Make</th>
            <th>Year</th>
            <th>Actions</th>
        </tr>
        <?php
        // 替换原SQL语句,使用LEFT JOIN关联clients表
        $sql = "SELECT 
                    m.id,
                    m.vin,
                    m.model,
                    m.description,
                    m.make,
                    m.year,
                    c.full_name
                FROM machines m
                LEFT JOIN clients c ON m.client_id = c.id
                ORDER BY m.year DESC";
        $res = mysqli_query($conn, $sql);

        if ($res == TRUE) {
            $count = mysqli_num_rows($res);
            $sn = 1;

            if ($count > 0) {
                while ($rows = mysqli_fetch_assoc($res)) {
                    $id = $rows['id'];
                    $vin = $rows['vin'];
                    // 读取关联得到的客户姓名,空值时显示默认文案
                    $client_name = !empty($rows['full_name']) ? $rows['full_name'] : '未绑定客户';
                    $model = $rows['model'];
                    $description = $rows['description'];
                    $make = $rows['make'];
                    $year = $rows['year'];
        ?>
                    <tr>
                        <td><?php echo $sn++; ?></td>
                        <td><?php echo $vin; ?></td>
                        <td><?php echo $model; ?></td>
                        <!-- 输出客户姓名替换原client_id -->
                        <td><?php echo $client_name; ?></td>
                        <td><?php echo $description; ?></td>
                        <td><?php echo $make; ?></td>
                        <td><?php echo $year; ?></td>
                        <td>
                            <a href="<?php echo SITEURL; ?>/update-machine.php?id=<?php echo $id; ?>" class="main-btn">Update Machine</a>
                            <a href="<?php echo SITEURL; ?>/delete-machine.php?id=<?php echo $id; ?>" class="danger-btn">Delete Machine</a>
                        </td>
                    </tr>

说明:如果你的clients表和machines表的关联字段不是machines.client_id对应clients.id,只需要调整JOIN后面的ON条件匹配你实际的关联字段即可。


内容的提问来源于stack exchange,提问作者Edvard Supica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:01:15