Populating a simple list box in PHP from PostgreSQL

46 views Asked by At

I'm new to PHP; however, I know how dynamic lists usually work in other platforms. I know how pg_query and its sibling members of that API work... sort of.

I don't have anything running, yet... just trying to get started.

1

There are 1 answers

3
AudioBubble On

Given PHP script will populate an HTML ListBox using data from DB (column of a table)

<?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);

?>