如何使用PHP在表中显示pg_query结果?

vecaoik1  于 2023-01-04  发布在  PHP
关注(0)|答案(2)|浏览(95)

我试图在一个格式整齐的表格中显示我的查询结果,但是我对PHP还是个新手,所以我有点不知所措。

$dbconn = pg_connect("host=localhost port=5432 dbname=mary");
$result =  pg_query($dbconn, $selectStmt);
$resultArr = pg_fetch_all($result);
print_r($resultArr);

假设$selectStmt = SELECT State, Name FROM perez.pop WHERE Name LIKE '%Alabama%';当我打印这个时,我得到了以下内容:

Array ( [0] => Array ( [state] => 1 [name] => Alabama ) )

我如何将其放入一个表中,该表中的列是“state”和“name”沿着还有一列是我计划放置到另一个页面的链接?
另外,有人能解释一下当查询得到多行时$resultArr的外观吗?
编辑:我希望输出如下所示:

State       | Name        | Follow link
___________________________________________________
32          Alabama       <some link to a php page> 
2           Alabama       <another link>
zu0ti5jz

zu0ti5jz1#

您可以在数组中loop,并在循环时打印表,类似于

$resultArr = pg_fetch_all($result);
//print_r($resultArr);

echo '<table>
        <tr>
         <td>State</td>
         <td>Name</td>
        </tr>';

foreach($resultArr as $array)
{
    echo '<tr>
            <td>'. $array['State'].'</td>
            <td>'. $array['Name'].'</td>
          </tr>';
}
echo '</table>';
83qze16e

83qze16e2#

$query = pg_query("SELECT * FROM user");
$users_arr = pg_fetch_all($query);

// render thead
$thead = '<thead>
    <tr>';
        foreach($users_arr[0] as $key => $value) {
        $thead .= '<th>' . $key . '</th>';
        }
        $thead .= '</tr>
</thead>';

// render tbody
$tbody = '<tbody>';
    foreach($users_arr as $key => $value) {
    $tbody .= '<tr>';
        foreach($value as $k => $v) {
        $tbody .= '<td>' . $v . '</td>';
        }
        $tbody .= '</tr>';
    }
    $tbody .= '</tbody>';

// render table
$table = '<table>' . $thead . $tbody . '</table>';
echo $table;

相关问题