【问题标题】:Display data from mysql columns as rows in PHP在 PHP 中将 mysql 列中的数据显示为行
【发布时间】:2018-12-21 12:04:33
【问题描述】:

我正在尝试创建一个网站来显示预订系统的表格。 我在 mysql 数据库中有一个表,其中包含如下数据:

第二列是 post_id。预订详情使用相同的 post_id 提供。

我想创建一个 html 表,其中一行包含相同的预订详细信息,如下所示:

<html>
<head>
  <title>Booking</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      color: #588c7e;
      font-family: monospace;
      font-size: 25px;
      text-align: left;
    } 
    th {
      background-color: #588c7e;
      color: white;
    }
    tr:nth-child(even) {background-color: #f2f2f2}
  </style>
</head>
<body>
  <table>
    <tr>
      <th>Field14</th> 
      <th>Field15</th> 
      <th>Field16</th>
    </tr>
    <?php
      $conn = mysqli_connect("localhost", "admin", "", "test");
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      } 
      $sql = "SELECT _field_14, _field_15, _field_16 FROM booking";
      $result = $conn->query($sql);

    ?>
  </table>
</body>
</html>

【问题讨论】:

  • 代码?你试过什么吗?
  • MySQL pivot table的可能重复
  • 我知道,但是不运行 sql 查询就不可能吗?

标签: php html sql


【解决方案1】:

不要被枢轴查询技术吓到。就像 GROUPing 然后在简单的 case 语句上调用 MAX() 一样简单。

查询:

SELECT 
    `post_id`,
    MAX(CASE WHEN `metar_key` = '_field_14' THEN `meta_value` ELSE NULL END) AS `field 14`,
    MAX(CASE WHEN `metar_key` = '_field_15' THEN `meta_value` ELSE NULL END) AS `field 15`,
    MAX(CASE WHEN `metar_key` = '_field_16' THEN `meta_value` ELSE NULL END) AS `field 16`
FROM `booking`
GROUP BY `post_id`
HAVING field14 IS NOT NULL AND field15 IS NOT NULL AND field16 IS NOT NULL
ORDER BY `post_id`;

*edit:HAVING 子句省略了完全由NULL 值组成的生成行——按照 OP 的要求。 然后像往常一样处理结果集行。

结果集:

post_id |   field 14  | field 15  |  field 16
--------|-------------|-----------|-----------
  490   |     IND     |   LHSM    | 2018-07-07
  491   |     ERK     |   LHKE    | 2018-07-08

这是一个代码 sn-p,包含错误检查点,向您展示如何处理结果集:

echo '<body>';
if (!$conn = new mysqli('localhost', 'admin', '', 'test')) {
    echo 'Connection Error'; // $conn->connect_error;  // never show the exact error message to the public
} else {
    $pivot = "SELECT 
                `post_id`,
                MAX(CASE WHEN `metar_key` = '_field_14' THEN `meta_value` ELSE NULL END) AS `field14`,
                MAX(CASE WHEN `metar_key` = '_field_15' THEN `meta_value` ELSE NULL END) AS `field15`,
                MAX(CASE WHEN `metar_key` = '_field_16' THEN `meta_value` ELSE NULL END) AS `field16`
            FROM `booking`
            GROUP BY `post_id`
            ORDER BY `post_id`";
    if (!$result = $conn->query($pivot)) {
        echo 'Syntax Error'; // $conn->error;  // never show the exact error message to the public
    } else {
        if (!$result->num_rows) {
            echo 'No Rows Returned From Pivot Query';
        } else {
            echo '<table>';
                echo '<tr><th>Field14</th><th>Field15</th><th>Field16</th></tr>';
                while ($row = $result->fetch_assoc()) {
                    echo "<tr><td>{$row['field14']}</td><td>{$row['field15']}</td><td>{$row['field16']}</td></tr>";
                }
            echo '</table>';
        }
        // $result->free();  // just a consideration
    }
    // $conn->close();  // just a consideration
}
echo '</body>';

【讨论】:

  • 谢谢,是的,我知道我可以用 sql 查询来做到这一点,但数据库的值是不断变化的。是否可以在 html 表中运行和显示查询结果?
  • 我花了整整 15 分钟试图找到完美的副本来结束,但所有其他的都更复杂。这个问题很基本。
  • 您有动态/无限数量的metar_key 值?你应该澄清你的问题。制作一个列数未知的 html 表格比较棘手。
  • @Bence 如果您使用 Brian 的解决方案,当您从指定字段之一中缺少值时,您将生成警告。除了这种糟糕的做法之外,Brian 的回答是进行迭代查询调用,这不是最佳做法。你对我的回答有什么不明白的地方吗?我正在向您展示最佳实践。
  • 或者你可以测试我最好的盲猜:(在 GROUP BY 子句之后和 ORDER BY 子句之前)HAVING field14 IS NOT NULL AND field15 IS NOT NULL AND field16 IS NOT NULL AND field17 IS NOT NULL AND field18 IS NOT NULL。我宁愿提供一个智能的基于查询的解决方案,而不是一个 php 条件——使用 php 不会那么聪明/干净/直接。
【解决方案2】:

试试这个...

<html>
<head>
  <title>Booking</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
      color: #588c7e;
      font-family: monospace;
      font-size: 25px;
      text-align: left;
    } 
    th {
      background-color: #588c7e;
      color: white;
    }
    tr:nth-child(even) {background-color: #f2f2f2}
  </style>
</head>
<body>
  <table>
    <tr>
      <th>Post_id</th>
      <th>Field14</th>
      <th>Field15</th> 
      <th>Field16</th>
    </tr>
    <?php
      $conn = mysqli_connect("10.0.1.1", "user", "pwd", "mydb");
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error); 
      }

      $sql = "SELECT DISTINCT(POST_ID) from booking";
      $result = $conn->query($sql);

if ($result->num_rows > 0) {

      while ($row = $result->fetch_assoc()) {

        $idsql = "select metar_key, meta_value from booking where POST_ID=\"".$row["POST_ID"]."\"";
        $idresult = $conn->query($idsql);

    while ($id = $idresult->fetch_assoc()) {
      $var[$id["metar_key"]] = $id["meta_value"];
        }

        echo "<tr>\n";
        echo "<td>".$row["POST_ID"]."</td>\n";
        echo "<td>".$var["_field_14"]."</td>\n";
        echo "<td>".$var["_field_15"]."</td>\n";
        echo "<td>".$var["_field_16"]."</td>\n";
        echo "</tr>\n";
      }
}


/*
      $sql = "SELECT _field_14, _field_15, _field_16 FROM booking";
      $result = $conn->query($sql);
*/

    ?>
  </table>
</body>
</html>

【讨论】:

    【解决方案3】:

    我不知道我是否做对了,但我认为你必须加入。假设第一个表是表 A,包含预订详细信息的表是表 B。您的请求将是:

    SELECT post_id, field14, field15, field16 FROM B WHERE post_id IN (SELECT post_id FROM A);
    

    【讨论】:

      【解决方案4】:
          <html>
          <head>
            <title>Booking</title>
            <style>
              table {
                border-collapse: collapse;
                width: 100%;
                color: #588c7e;
                font-family: monospace;
                font-size: 25px;
                text-align: left;
              } 
              th {
                background-color: #588c7e;
                color: white;
              }
              tr:nth-child(even) {background-color: #f2f2f2}
            </style>
          </head>
          <body>
            <table>
              <tr>
                <th>Field14</th> 
                <th>Field15</th> 
                <th>Field16</th>
              </tr>
          <?php while($res = mysqli_fetch_array($result)) { 
          echo'<tr>';
          echo"<td>".$res['_field_14']."</td>";
          echo"<td>".$res['_field_15']."</td>";
          echo"<td>".$res['_field_16']."</td>";
      }
         ?>
            </table>
          </body>
          </html>
          <?php
            $conn = mysqli_connect("localhost", "admin", "", "test");
            // Check connection
            if ($conn->connect_error) {
              die("Connection failed: " . $conn->connect_error);
            } 
            $sql = "SELECT _field_14, _field_15, _field_16 FROM booking";
            $result = $conn->query($sql);
      
          ?>
      

      此代码。希望对你有帮助

      【讨论】:

        【解决方案5】:
        <?php
        $row = array(
            array(
                'meta_id' => 1556,
                'post_id' => 490,
                'metar_key' => '_field_14',
                'meta_value' => 'IND'
            ),
            array(
                'meta_id' => 1557,
                'post_id' => 490,
                'metar_key' => '_field_15',
                'meta_value' => 'LHSM'
            ),
            array(
                'meta_id' => 1558,
                'post_id' => 490,
                'metar_key' => '_field_16',
                'meta_value' => '2018-07-07'
            ),
            array(
                'meta_id' => 1558,
                'post_id' => 490,
                'metar_key' => '_field_16',
                'meta_value' => '2018-07-07'
            ),
            array(
                'meta_id' => 1559,
                'post_id' => 491,
                'metar_key' => '_field_14',
                'meta_value' => 'ERK'
            ),
            array(
                'meta_id' => 1560,
                'post_id' => 491,
                'metar_key' => '_field_15',
                'meta_value' => 'LHKE'
            ),
            array(
                'meta_id' => 1561,
                'post_id' => 491,
                'metar_key' => '_field_16',
                'meta_value' => '2018-07-08'
            )
        );
        
        $table_tr = array();
        $table_td = array('POST_ID');
        foreach($row as $k => $v) {
            if(!in_array(strtoupper(substr($v['metar_key'], 1)), $table_td)) {
                $table_td[] = strtoupper(substr($v['metar_key'], 1));
            }
            if(!isset($table_tr[$v['post_id']]['POST_ID'])) {
                $table_tr[$v['post_id']]['POST_ID'] = $v['post_id'];
            }
            $table_tr[$v['post_id']][strtoupper(substr($v['metar_key'], 1))] = $v['meta_value'];
        }
        ?>
        
        <!DOCTYPE HTML>
        <html>
            <head>
                <style>
                    table,table tr th, table tr td { border:1px solid #000; }
                    table { width: 200px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse; }   
                </style>
            </head>
            <body>
                <table>
                    <tr>
                        <?php
                        foreach($table_td as $k => $v) {
                            echo '<th>'.$v.'</th>';
                        }
                        ?>
                    </tr>
                    <?php
                    foreach($table_tr as $tr) {
                        echo '<tr>';
                        foreach($table_td as $k => $v) {
                            echo '<td>'.(isset($tr[$v]) ? $tr[$v] : '-').'</td>';
                        }
                        echo '</tr>';
                    }
                    ?>
                </table>
            </body>
        </html>
        

        这样的结果。 enter image description here

        $row 是您的 mysql 数据库数据信息,您也可以通过代码获取它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-30
          • 1970-01-01
          相关资源
          最近更新 更多