pdo规范化mysql表

时间:2017-06-08 20:30:10

标签: mysql sql

我对标准化很新。我理解它如何组织表格的概念,但我没有看到如何使用数据正确显示。

我有3张桌子:

employees:
id  |  name
1     user1
2     user2
2     user3

shops:
shop_id  | shop
1          shop1
2          shop2
3          shop3
4          shop4
5          shop5

shop_employees:
shops_employees_id  |  employee_id  |  shop_id
1                      1               1
2                      1               2
3                      2               4
4                      3               3
5                      3               5

但我明白了:

user1 shop1
user1 shop2
user2 shop4
user3 shop3
user3 shop5

如何将它们排成一行,如:

user1 shop1 shop2
user2 shop4
user3 shop3 shop5

这是我的代码:

<?php

...

try
{
    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

class crud
{
    private $db;

    function __construct($DB_con)
    {
        $this->db = $DB_con;
    }


    public function getID($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM employees WHERE id=:id");
        $stmt->execute(array(":id"=>$id));
        $editRow=$stmt->fetch(PDO::FETCH_ASSOC);
        return $editRow;
    }


    public function dataview($query)
    {
        $stmt = $this->db->prepare($query);
        $stmt->execute();

        if($stmt->rowCount()>0)
        {
            while($row=$stmt->fetch(PDO::FETCH_ASSOC))
            {

                ?>

                <tr>
                <td><?php print($row['id']); ?></td>
                <td><?php print($row['name']); ?></td>
                <td><?php print($row['shop']); ?></td>

                <?php

            }
        }
        else
        {
            ?>
            <tr>
            <td colspan="8" class="text-center danger"> Nothing founds...</td>
            </tr>
            <?php
        }

    }


}

$crud = new crud($DB_con);


?>


<table>


<?php

    $query = "

    SELECT emp.id,
           emp.name,
           sh.shop
    from employees AS emp 
         INNER JOIN shops_employees AS se ON (emp.id     = se.employee_id)
         INNER JOIN shops           AS sh ON (sh.shop_id = se.shop_id)
    ORDER BY emp.name,
             sh.shop;";




    $crud->dataview($query);

?>


</table>

0 个答案:

没有答案