PHP显示简单的LEFT OUTER JOIN

时间:2015-09-14 18:05:41

标签: php mysql

我加入了(LEFT OUTER JOIN)两个表(user和userrole)来显示四个字段的列表(三个来自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_users_roles.html.php):

<?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>

感谢您的帮助!

0 个答案:

没有答案