PHP显示简单的左外连接
我连接(左外连接)两个表(user和userrole)以显示四个字段的列表(三个来自PHP显示简单的左外连接,php,mysql,Php,Mysql,我连接(左外连接)两个表(user和userrole)以显示四个字段的列表(三个来自user,一个来自userrole)。SELECT语句在phpMyAdmin中工作,但我的PHP必须至少有一个错误,因为我无法显示它。这可能与如何从联接表中引用列有关,因为如果没有它,它就可以工作 以下是控制器代码: //******************* User role ***********************// if(isset($_GET['role'])) { inc
user
,一个来自userrole
)。SELECT语句在phpMyAdmin中工作,但我的PHP必须至少有一个错误,因为我无法显示它。这可能与如何从联接表中引用列有关,因为如果没有它,它就可以工作
以下是控制器代码:
//******************* User role ***********************//
if(isset($_GET['role']))
{
include '../includes/dbconnect-local.php';
try
{
$sql = 'SELECT name, userid, email, roleid
FROM user LEFT OUTER JOIN userrole
ON user.id = userrole.userid
ORDER BY name';
$result = $db->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching role data.';
include 'error.html.php';
exit();
}
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$roles[] = array(
'name' => $row['name'],
'userid' => $row['userid'],
'email' => $row['email'],
'roleid' => $row['roleid']
);
}
include 'display_users_roles.html.php';
header('Location: .');
exit();
}
下面是HTML(display\u users\u roles.HTML.php):
用户角色
用户角色
名称
身份证件
电子邮件
角色
谢谢你的帮助 代码当前在哪里停止,
获取角色数据时出错?标题('Location:')我觉得这个电话很奇怪。为什么会这样?如果你打开了输出缓冲,它甚至可能是你的问题的原因,因为它在显示页面后立即重定向你。我发现了问题@克里斯85,你说得对。标题需要删除。然而,在此之前,问题是我忽略了包含exit();之后包括。代码正在向标题前进,就像它应该的那样。有趣的是,代码是多么顺从!现在可以了。谢谢你的考虑。我欢迎您对代码有任何其他想法。感谢您抽出时间来回顾这篇文章!结尾应该是:包括“display_users_roles.html.php”;退出();}我建议不要使用查询
。我总是使用prepare
和execute
。这样,就可以很容易地添加,而不是通过黑客破解来逃避以后准备的语句。@chris85谢谢。我读的教科书使用query()获得结果集。出于安全考虑,您是否建议使用$s=$db->prepare($sql),$s->execute()作为替换?代码当前停在哪里,获取角色数据时出错?标题('Location:')我觉得这个电话很奇怪。为什么会这样?如果你打开了输出缓冲,它甚至可能是你的问题的原因,因为它在显示页面后立即重定向你。我发现了问题@克里斯85,你说得对。标题需要删除。然而,在此之前,问题是我忽略了包含exit();之后包括。代码正在向标题前进,就像它应该的那样。有趣的是,代码是多么顺从!现在可以了。谢谢你的考虑。我欢迎您对代码有任何其他想法。感谢您抽出时间来回顾这篇文章!结尾应该是:包括“display_users_roles.html.php”;退出();}我建议不要使用查询
。我总是使用prepare
和execute
。这样,就可以很容易地添加,而不是通过黑客破解来逃避以后准备的语句。@chris85谢谢。我读的教科书使用query()获得结果集。出于安全考虑,您是否建议使用$s=$db->prepare($sql),$s->execute()作为替换?
<?php
include '../includes/helpers.inc.php';
?><!DOCTYPE html>
<html lang="en">
<head>
<title>User roles</title>
<meta charset="utf-8">
</head>
<body>
<h1>User roles</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<?php foreach($roles as $role): ?>
<tr>
<td><?php echo htmlspecialchars($role['name']); ?></td>
<td><?php echo htmlspecialchars($role['userid']); ?></td>
<td><?php echo htmlspecialchars($role['email']); ?></td>
<td><?php echo htmlspecialchars($role['roleid']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>