Reputation: 43
I am new to PHP, hoping for some help please. I am trying to populate an HTML dropdown list with data from my SQL database. I would like to be able to select an item from a dropdown list that would then fill an HTML table with the associated record from the database. So far I have managed to connect to my database and retrieve all of the data from the relevant table.
Can someone please help me set this up to work through the dropdown list?
Thanks
<?php
$username = 'root';
$password = '';
$conn = new PDO( 'mysql:host=localhost; dbname=Oaktown', $username, $password );
$sql ="SELECT RoundNumber, RoundDate, HomeTeam, HomeTeamScore, AwayTeam, AwayTeamScore FROM Fixture";
$statement = $conn->prepare( $sql );
$statement->execute();
$results = $statement->fetchAll( PDO::FETCH_ASSOC );
?>
<h2>Competitions</h2>
<article>
<p id="TableHeader1">Fixture Information</p>
<P>Select Round and Game number from the dropdown list under Round Number.</P>
<br>
<br><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p id="TableHeader2">Round Number
<select style="width:250px"></select>  <input class="button"
type="submit" name="Get" value="Get Fixture Results"></p>
<p id="TableHeader2">Results</p>
<table class="table">
<tr><td><b>Round Number:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundNumber'];
}
?>
</tr>
<tr>
<td><b>Round Date:</b></td>.
<?php foreach( $results as $row ){
echo "<td>";
echo $row['RoundDate'];
}
?>
</tr>
<tr>
<td><b>Home Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeam'];
}
?>
</tr>
<tr>
<td><b>Home Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['HomeTeamScore'];
}
?>
</tr>
<tr>
<td><b>Away Team:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeam'];
}
?>
</tr>
<tr>
<td><b>Away Team Score:</b></td>
<?php foreach( $results as $row ){
echo "<td>";
echo $row['AwayTeamScore'];
}
?>
<td colspan="2><?php echo $message; ?>"></td>
</tr>
</table>
</form>
Upvotes: 4
Views: 4893
Reputation: 4057
Using a similar block of code like the one you use for the tables you can do something like this:
<select>
<?php foreach( $results as $row ){
echo "<option value='" . $row['value column'] . "'>" . $row['text column'] . "</option>";
}
?>
</select>
if you don't have or need a pair of values then you can simply do this:
<select>
<?php foreach( $results as $row ){
echo "<option>" . $row['text column'] . "</option>";
}
?>
</select>
Upvotes: 4