PHP关联表获取导师用户名失败,报Undefined array key 'id'错误
问题描述
我目前可以正常查看联系人列表,现在希望添加查看客户对应导师/教员信息的功能。导师用户名存储在accounts表中,导师ID存储在contacts表内。
按教程尝试关联两张表后,页面完全无法显示任何内容;旧代码除了导师信息外,其他内容均可正常展示。报错信息:Warning: Undefined array key "id"
新尝试的关联查询代码
$stmt = $pdo->prepare('SELECT c.id , c.name , c.last_name , c.mobile_number , c.status , a.username as mentorname FROM contacts c LEFT JOIN accounts a ON c.mentor = a.id WHERE c.id = ?;'); $stmt->execute([$_GET['c.id']]); $fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC); }
页面展示代码
<?php if($fullContactInfo == null){ echo "<tr><td>No Record Found!</td></tr>"; }else{ foreach($fullContactInfo as $info){ ?> <tr> <td><?php echo $info['name']; ?> <?php echo $info['last_name']; ?></td> <td><?php echo $info['mobile_number']; ?></td> <td><?php echo $info['status']; ?></td> <td><?= $info['mentorname']; ?></td>
表结构示例
Contacts表
ID: 1 Name: Joe Blogs Mobile: 1889454 Status: Current Mentor: 25
Accounts表
ID: 25 Username: jbloggs
旧代码(可正常显示除导师外的信息)
$stmt = $pdo->prepare('SELECT id,name,last_name,mobile_number,status,dob,mentor,image FROM contacts'); $stmt->execute([$_GET['id']]); $fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC); if($fullContactInfo == true){ $stmt = $pdo->prepare('SELECT username FROM accounts WHERE id = ?'); $stmt->execute([ $fullContactInfo['mentor'] ]); $fullContactInfo1 = $stmt->fetch(PDO::FETCH_ASSOC);
问题解决
1. 修复参数错误
报错核心原因是新代码中使用了$_GET['c.id'],但实际URL传递的参数是id(旧代码中用的是$_GET['id']),将$_GET['c.id']改为$_GET['id']即可解决Undefined array key "id"的问题。
2. 优化查询与展示逻辑
- 单条联系人记录无需用
fetchAll(),改用fetch()获取一维数组更高效,避免冗余循环:
$stmt = $pdo->prepare('SELECT c.id , c.name , c.last_name , c.mobile_number , c.status , a.username as mentorname FROM contacts c LEFT JOIN accounts a ON c.mentor = a.id WHERE c.id = ?;'); $stmt->execute([$_GET['id']]); $fullContactInfo = $stmt->fetch(PDO::FETCH_ASSOC); // 替换fetchAll为fetch
- 对应展示代码简化为:
<?php if(!$fullContactInfo){ echo "<tr><td>No Record Found!</td></tr>"; }else{ ?> <tr> <td><?php echo $fullContactInfo['name']; ?> <?php echo $fullContactInfo['last_name']; ?></td> <td><?php echo $fullContactInfo['mobile_number']; ?></td> <td><?php echo $fullContactInfo['status']; ?></td> <td><?php echo $fullContactInfo['mentorname'] ?? '无导师'; ?></td>
- 用
??运算符处理导师ID不存在(或对应账号已删除)的情况,避免出现undefined index警告。
3. 旧代码的潜在问题说明
旧代码中用fetchAll()获取单条记录后,直接取$fullContactInfo['mentor']会报错,因为fetchAll()返回的是二维数组,正确写法应为$fullContactInfo[0]['mentor'],或者直接改用fetch()获取单条记录。
内容的提问来源于stack exchange,提问作者user19638812
相关产品推荐
相关产品推荐

