Dan Dan - 7 months ago 17
HTML Question

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.

Example:

On a page called 'createCD.php' I have this code:

echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`


This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.

Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):

Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>


What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.

I know I need to be using

<option selected ...>


but I'm not sure on the syntax to use.

Answer
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation

echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
    echo '<option value="'.$row['artID'].'"';
    if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
    echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
Comments