0

I have a php 'update' page in which I use an existing database record to load the field data into their respective input fields, to be edited by the user if they wish. Most of these are displayed in textboxes, which works fine including both the HTML and PHP inside a single echo statement like so:

<?php echo"<input type=\"text\" name=\"age\" value=\"{$age}\" class=\"textbox\"><br>"?>

The problem I'm having is trying to use a similar approach when it comes to attempting to use PHP to populate and set initial value in a dropdown box. Here is the associated code:

$query = "SELECT raceID, RaceName FROM races";
$result = $conn->query($query);

<?php echo
"<select value=\"{$racingIn}\">
while ($rowRace = $result->fetch_assoc()){
//add all rows in database collection to dropdown box for selection
<option name=\"racingIn\" value=\"{$rowRace['raceID']}\">{$rowRace['RaceName']}</option>;
}
</select><br>"
?>

It almost works, but I keep getting the error on pageload telling me that the $rowRace variable is undefined. I know this isn't the case as it is used elsewhere in the program and did work fine until the original 2 separate PHP spans were merged into one. I think it might be something to do with missing {} brackets around the PHP variables.

Any advice with this, whether it be fixing the existing or suggesting an easier approach, would be massively appreciated.

Thanks, Mark

2 Answers 2

1

Try like this:-

<select name="race">
<?php
while ($rowRace = $result->fetch_assoc()){
//add all rows in database collection to dropdown box for selection
?>
<option name="racingIn" value="<?php echo $rowRace['raceID'] ?>"><?php echo $rowRace['RaceName']; ?></option>
<?php
} ?>
</select>
Sign up to request clarification or add additional context in comments.

4 Comments

Oh dear... You should really clean this up.. Before people's eyes bleed out.
Thanks for your reply. The errors have disappeared but the dropdown list is empty when clicked on. Any idea what this might be?
@marcuthh no it shouldn't be empty if there is value in the database for the column RaceName.
Thanks, I had a conflict of brackets inside the quotation marks that meant the values were not being recognised. Thanks for taking the time to do this.
0

Assuming that there's a variable $selectedRaceID with the selected "raceID" value (similar to $age above):

echo '<select name="race">';
while ($row = $result->fetch_assoc()) {
    echo '<option value="'. $row['raceID'] .'"';
    echo ($selectedRaceID == $row['raceID']) ? ' selected' : '';
    echo '>'. $row['RaceName'] .'</option>';
}
echo '</select>';

I've also made your HTML valid (SELECT can't have a VALUE attribute, for example).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.