作为我学习OOP PHP的一部分,我创建了一个包含以下方法的数据库对象:
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = static::instantiate($row);
}
return $object_array;
}
我可以使用它来检索和访问单个表中的数据,但是当我尝试将它与连接表一起使用时,该对象仅向我提供主表中的数据,例如。
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
使用上面的查询,以下代码不会为s.name字段输出任何内容,但会正确列出members表中的所有字段。我知道MySQL查询正在访问数据,因为ORDER BY语句正确地对输出进行排序。
<?php foreach($members as $member): ?>
<tr>
<td><?php echo $member->name;?></td>
<td><?php echo $member->full_name();?></td>
<td><?php echo $member->getAge($member->dob);?></td>
<td><a href="member_edit.php?id=<?php echo $member->id;?>">Edit</a></td>
<td><a href="member_delete_confirm.php?id=<?php echo $member->id;?>">Delete</a></td>
</tr>
<?php endforeach; ?>
如果我使用print_r($ members)输出$ members,它只包含members表中的数据,如何访问从其他表中检索的数据?
由于
答案 0 :(得分:0)
你也需要在这里选择它们:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob";
$sql .= " FROM members AS m";
$sql .= " LEFT JOIN mbr_sections AS ms ON m.id = ms.member_id";
$sql .= " LEFT JOIN sections AS s ON ms.section_id = s.id";
$sql .= " ORDER BY s.organisation ASC, s.name ASC, m.lastName ASC, m.firstName ASC";
$sql .= " LIMIT {$per_page} ";
$sql .= " OFFSET {$pagination->offset()}";
$members = Member::find_by_sql($sql);
您只选择了name,id,firstName,lastName和dob。
以下是一个例子:
$sql = "SELECT s.name, m.id, m.firstName, m.lastName, m.dob, mbr_sections.field_you_want, sections.*";