PHP - Возврат таблицы SQL с оператором foreach, возвращая только значение первого столбца

Я пытаюсь отобразить таблицу SQL с помощью PHP, передав только имя таблицы, а затем вычислив количество строк и столбцов для правильного отображения таблицы.

До сих пор мне удалось получить имена столбцов, но у меня возникли проблемы с отображением большего, чем значение первого столбца, например:

ID | lastName | firstname | etc..
10 | 11 | 13 | 16 | 19 | etc..

Например.

Вот мой код для получения заголовков столбцов:

    $STH = $conn->prepare("SELECT * FROM $tableName");
    $STH->execute(); 

    $STH = $conn->query("SELECT * FROM $tableName");
    $STH->setFetchMode(PDO::FETCH_ASSOC);

    $headerQuery = $conn->prepare("DESCRIBE employees");
    $headerQuery->execute();
    $table_fields = $headerQuery->fetchAll(PDO::FETCH_COLUMN);

    $num_fields = count($table_fields);

    echo "<table border='1'>
    <tr>";

    for ($x=0;$x<$num_fields;$x++)
        {
            echo "<th>$table_fields[$x]</th>";
        }

    echo "</tr>";

А вот код для получения значений, который работает некорректно:

for ($x=0;$x<$num_fields;$x++)
        {
            echo "<tr>";
            foreach ($table_fields as &$fieldname) 
                {
                    while($row = $STH->fetch())
                        {
                            echo "<td>" . $row[$fieldname] . "</td>";
                        }
                }
            echo "</tr>";
        }

Любая помощь чрезвычайно ценится, наряду с любыми советами о том, как я могу сделать то, что у меня уже есть, более эффективно.

Спасибо!


person Nathan Aston    schedule 27.11.2013    source источник
comment
какой запрос в $STH   -  person WayneC    schedule 28.11.2013
comment
Ой, извините - я пропустил это, добавил к основному вопросу.   -  person Nathan Aston    schedule 28.11.2013


Ответы (1)


Я чувствую себя таким идиотом из-за того, что пропустил это, я использовал совершенно неправильную переменную для подсчета строк (и не говоря уже о том, что структура цикла тоже была неправильной)

    $fieldValue = $conn->query("SELECT * FROM $tableName"); 
    $fieldValue->setFetchMode(PDO::FETCH_ASSOC); // We'll come back to this later.

    $headerQuery = $conn->prepare("DESCRIBE $tableName"); // Get our table headers from the input table.
    $headerQuery->execute();
    $table_fields = $headerQuery->fetchAll(PDO::FETCH_COLUMN);

    $num_fields = count($table_fields); // Find out how many headers there actually are and make it a useful variable.

    $sql = "SELECT COUNT(*) AS rowscount FROM $tableName"; // Run a count query to find out how many rows are in the table.
    $results = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); // n.b. - This comes out as a multi-dimensional array. This is annoying.
    $num_rows = $results[0]['rowscount']; // Get the value out of the array so it's not clogging up the code.

    // echo ("Number of rows: " . $num_rows); // Debugging - this was showing as 0 or 1 for the longest time, until I realised it was multidimensional above.

    echo "<table border='1'><tr>";  // Build the table

    for ($x=0;$x<$num_fields;$x++) // Working through the headers one by one.
        {
            echo "<th>$table_fields[$x]</th>"; // This was the easy bit, displaying the column headers.
        }

    echo "</tr>"; 

    for($x=0;$x<$num_rows;$x++) // Now we need to go down the rows, 
        {
            while($row = $fieldValue->fetch()) // This is where our $fieldValue comes in, pluck out the value of each field before putting it in.
                {
                    echo "<tr>";
                    foreach ($table_fields as &$fieldname) 
                    {
                        echo "<td>" . $row[$fieldname] . "</td>"; 
                    }
                    echo "</tr>";
                }           
        }   
    $conn = null; // Terminate the connection. You're not needed anymore.
    echo "</table>";   //Close the table
person Nathan Aston    schedule 28.11.2013