Displaying an associative array in PHP

前端 未结 6 1862
南旧
南旧 2021-01-23 04:20

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the ar

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 04:52

    The following should work:

    $rows = mysql_query("select * from whatever");
    if ($rows) {
        $header = true;
        while ($record = mysql_fetch_assoc($rows)) {
            if ($header) {
                echo '';
                foreach (array_keys($record) AS $col) {
                    echo ''.htmlspecialchars($col).'';
                }
                echo '';
                $header = false;
            }
            echo '';
            foreach (array_values($record) AS $col) {
                echo ''.htmlspecialchars($col).'';
            }
            echo '';
        }
    }
    

    (Yes, blatant mod of Fosco's code)

    This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

提交回复
热议问题