php / oracle - 根据列数创建一个表

时间:2014-12-03 14:10:33

标签: php html sql oracle

我有一个查询(这里没有显示,因为它不是问题)给我另一个这样的查询:

SELECT NAME, ID FROM TABLE1

SELECT USER, EMAIL, NUMBER FROM TABLE2

这取决于相应表中的列数。

所以我可以将这些列用于php变量......这是完美的。

但是:我如何根据php中的列数创建动态html表,因为它可以是1列或X列。

我的例子必须是:

...
<td>NAME</td>
<td>ID</td>
...

...
<td>USER</td>
<td>EMAIL</td>
<td>NUMBER</td>
...

在php中,我的代码就像这样:

...
foreach ($rows as $value) {
        $res .= '
              <tr>
                <td>'.$value["NAME"].'</td>
                <td>'.$value["ID"].'</td>
              </tr>
              ';
        }
...

任何解决方案吗?

2 个答案:

答案 0 :(得分:0)

PDO的一个例子

 <?php
    echo "<table style='border: solid 1px black;'>";
    echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>Email</th><th>Reg date</th></tr>";

    class TableRows extends RecursiveIteratorIterator {
        function __construct($it) {
            parent::__construct($it, self::LEAVES_ONLY);
        }

        function current() {
            return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
        }

        function beginChildren() {
            echo "<tr>";
        }

        function endChildren() {
            echo "</tr>" . "\n";
        }
    }

    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDBPDO";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT * FROM MyGuests");
        $stmt->execute();

        // set the resulting array to associative
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

        foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
            echo $v;
        }
        $dsn = null;
        }
    catch(PDOException $e)
        {
        echo "Error: " . $e->getMessage();
        }
    $conn = null;
    echo "</table>";
    ?> 

答案 1 :(得分:0)

我找到了这样的解决方案:

$ first = true;
Foreach ($row as $rows) {
    $keys = [];

    If ($first) {
Foreach( $row as  $key => $value) // dynamic table header
{
        Echo ‘<th>’.$key.’</th>’
        $keys[] = $key;
}
  $first = false;
}
…
For int (i=0;iy$keys.count();i++){ // dynamic table row
Echo ‘<tr>’.$row[keys[i]].</tr>’;
…
}