mySQL查询将列数据动态转换为列名

时间:2015-12-17 23:17:19

标签: php mysql database

我正在尝试从ZenCart数据库创建一个“运行表”的甜甜圈订单。我阅读了十几个问题,以获得[Jeff Lee对问题的回答]:SQL query to rebuild a table using its dynamic row data for column names。由于我使用MySQL,我认为我需要生成动态查询,因为我的'ProductName'数据发生了变化。

我编写了以下代码,它生成一个类似于示例数据库表的HTML表格,但我不知道如何将他的解决方案合并到我的代码中,因为我不是从数据库表开始而是查询结果 - 集。

我将尝试从现有查询创建数据库表以使用Jeff的解决方案,但我认为首选方法是将他的代码合并到我的查询中,我只是不知道如何。

我使用的是PHP / 5.6.11和MySQL / 5.6.25

<?php 
    echo 'Attempt connection to the [donutsdb] database';
    print '<br />';
    require("includes/connect2donutsdb.php");
?>

<?php
//this script will query the 'orders' and 'orders_products' tables
//and combine the information based on the 'orders_id' field
//I added aliases to improve the query readability
try {
    echo '[donutsdb]';
    print '<br />';
    $query = "
    SELECT
        o.orders_id AS 'O_OID', o.customers_name AS 'O_CName',
        p.products_name AS 'P_PName', p.products_quantity AS 'P_PQuant'
    FROM
        orders AS o
    INNER JOIN orders_products AS p
    ON o.orders_id=p.orders_id
    ";
    //first pass just gets the column names
    print "<table> \n";
    $result = $dbh->query($query);
    //return only the first row (we only need field names)
    $row = $result->fetch(PDO::FETCH_ASSOC);
    print " <tr> \n";
    foreach ($row as $field => $value){
        print " <th>$field</th> \n";
    } // end foreach
    print " </tr> \n";
    //second query gets the data
    $data = $dbh->query($query);
    $data->setFetchMode(PDO::FETCH_ASSOC);
    foreach($data as $row){
        print " <tr> \n";
        foreach ($row as $name=>$value){
            print " <td>$value</td> \n";
        } // end field loop
        print " </tr> \n";
    } // end record loop
    print "</table> \n";
print '<br />';
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>

我的代码生成一个HTML表格,其结构如下:

 O_OID | O_CName | P_PName            | P_PQuant 
 1     |  mark   |  Glazed            |  12 
 2     |  John   |  Glazed            |  8 
 2     |  John   |  Bavarian Cream    |  4 
 3     |  mark   |  Chocolate Dipped  |  12 
 4     |  Kevin  |  Donut Holes       |  10 
 5     |  Kevin  |  Peanut Butter     |  1 
 5     |  Kevin  |  Blueberry         |  2 

我想要实现的目标是:

O_OID | O_CName | Glazed | Bavarian Cream | Chocolate Dipped | Donut Holes | Peanut Butter | Blueberry
1     |  mark   |  12    |  0             |  0               |  0          |  0            |  0
2     |  John   |  8     |  4             |  0               |  0          |  0            |  0
3     |  mark   |  0     |  0             |  12              |  0          |  0            |  0
4     |  Kevin  |  0     |  0             |  0               |  10         |  1            |  2

0 个答案:

没有答案