在PHP中从PostgreSQL填充简单的列表框

qkf9rpyu  于 2023-04-28  发布在  PHP
关注(0)|答案(1)|浏览(88)

我是PHP新手;但是,我知道动态列表在其他平台中通常是如何工作的。我知道pg_query及其API的兄弟成员是如何工作的。算是吧
我还没有运行任何东西。只是想开始

rekjcdws

rekjcdws1#

给定的PHP脚本将使用数据库中的数据填充HTML列表框(表的列)

<?php

$host = 'localhost';
$dbname = 'your_database_name';
$user = 'your_username';
$password = 'your_password';
$conn = pg_connect("host=$host dbname=$dbname user=$user password=$password");

// Check connection
if (!$conn) {
    die("Connection failed: " . pg_last_error());
}

// Fetch data ""ColumnOfYourChoice1" is like ID, ColumnOfYourChoice2" is like Value "from "YourTable"
$query = "SELECT "ColumnOfYourChoice1", "ColumnOfYourChoice2" FROM YourTable";
$result = pg_query($conn, $query);

if (!$result) {
    die("Query failed: " . pg_last_error());
}

// Create HTML list box
echo '<select name="YourTable">';

// Populate list box with YourTable data
while ($row = pg_fetch_assoc($result)) {
    $ColumnOfYourChoice1 = $row['ColumnOfYourChoice1'];
    $ColumnOfYourChoice2 = $row['ColumnOfYourChoice2'];
    echo "<option Value=\"$ColumnOfYourChoice1\">$ColumnOfYourChoice2</option>";
}

echo '</select>';

// Close PostgreSQL connection
pg_close($conn);

?>

相关问题