I am filling a select box with elements from a SQL database and I want to set the default value in the select box to the option that's eventID = $eventID ($eventID is a variable which we get from the previous page).
My idea was to use an if statement to check if eventID = $eventID and then set that option to selected. Like this:
echo "<p>catDesc</p><select name='catID'>";
while ($rowObj = $catDescQueryResult->fetchObject()) {
if (eventID == $currentEventID) {
echo "<option value='{$rowObj->catID}' selected>{$rowObj->catDesc}</option>";
}
echo "<option value='{$rowObj->catID}'>{$rowObj->catDesc}</option>";
}
echo "</select>";
Here is the full PHP script:
<?php
$eventID = filter_has_var(INPUT_GET, 'eventID') ? $_GET['eventID'] : null;
if (empty($eventID)) {
echo "<p>Please <a href='admin.php'>choose</a> an Event.</p>\n";
}
else {
try {
require_once("dbConnect.php");
$dbConn = getConnection();
// Query to retrieve event data from database
$sqlQuery = "SELECT eventID, eventTitle,eventStartDate, eventEndDate, eventPrice, eventDescription, NE_category.catDesc, NE_venue.venueName, NE_venue.venueID, NE_events.catID
FROM NE_events
INNER JOIN NE_category
ON NE_category.catID = NE_events.catID
INNER JOIN NE_venue
ON NE_venue.venueID = NE_events.venueID
WHERE eventID = $eventID";
$queryResult = $dbConn->query($sqlQuery);
$rowObj = $queryResult->fetchObject();
// Edit form fields are populated with existing data (all fields are editable, except the eventID)
echo "<h1>Update '{$rowObj->eventTitle}'</h1>
<form id='UpdateEvent' action='updateEvent.php' method='get'>
<p>Event ID <input type='text' name='eventID' value='$eventID' readonly /></p>
<p>eventTitle <input type='text' name='eventTitle' size='50' value='{$rowObj->eventTitle}' /></p>
<p>eventStartDate <input type='text' name='eventStartDate' value='{$rowObj->eventStartDate}' /></p>
<p>eventEndDate <input type='text' name='eventEndDate' value='{$rowObj->eventEndDate}' /></p>
<p>eventPrice <input type='text' name='eventPrice' value='{$rowObj->eventPrice}' /></p>
<p>eventDescription <textarea name='eventDescription' rows='3' cols='100'/>{$rowObj->eventDescription}</textarea></p>
";
$catDescQuery = "SELECT catDesc, catID
FROM NE_category
";
$catDescQueryResult = $dbConn->query($catDescQuery);
echo "<p>catDesc</p><select name='catID'>";
while ($rowObj = $catDescQueryResult->fetchObject()) {
if (eventID == $currentEventID) {
echo "<option value='{$rowObj->catID}' selected>{$rowObj->catDesc}</option>";
}
echo "<option value='{$rowObj->catID}'>{$rowObj->catDesc}</option>";
}
echo "</select>";
}
// If the above try block is unsuccessful the user will be presented with the message below
catch (Exception $e){
echo "<p>Event details not found: ".$e->getMessage()."</p>\n";
}
}
?>
</select>