Ollie
Ollie

Reputation: 37

Display data from database as option in a select

I'm coding a website for an online DVD rental and booking system and trying to call into a dropdown menu the DVDID which is the primary key and the title of the DVDs in my phpmyadmin data base but when I try to call the ID in it does not work. Any help would be appreciated.

<form name="FrmAmend" method="post" action="amenddvd2.php">
Select from the list below<br>
<select name="Film" title="Select DVD">
    <option value="" selected disabled>Select DVD</option>
<?php

$result = mysqli_query($con, "SELECT `DVDID`, `Title` FROM tbldvd;");
$row = mysqli_fetch_assoc($result);
foreach ($result as $row) {
    echo "<option value='" . $row['DVDID'] . $row['Title'] . "'>" . $row['DVDID'] . $row['Title'] . "</option>";

}
?>
</select><br>
<a href="menu.php"</a>Return To Main Menu<br>
<input type="submit" name="Submit" value="Select DVD">
</a>
</form>

Upvotes: 1

Views: 81

Answers (1)

anon
anon

Reputation:

The issue you have is the way you collect the data, you have the following;

$row = mysqli_fetch_assoc($result);
foreach ($result as $row) {

mysqli_fetch_assoc collects a single row from the result set, a better way to do this, would be to replace the above and use the following;

while ($row = mysqli_fetch_assoc($result) {

And this will get the results out of the database, row by row and print these without having to have changes inside the loop

Looping in a while, using mysqli_fetch_assoc collects each row, one at a time allowing you to use this more effectively.
So, if you have the following data;

DVDID    Title
1        ABC
2        DEF

A while loop collects the rows, one at a time, for each row in your result set, where a single fetch_assoc will collect the first that appears in the result set and nothing more

As an additional, you have the following HTML;

<a href="menu.php"</a>Return To Main Menu<br>

This is not valid as HTML, from this, it looks like you want "*Return To Main Menu" to be the hyperlink, so replacing the above with the following will resolve this issue;

<a href="menu.php">Return To Main Menu</a><br>

This adds the close to the first "a" (>) and moves the text to within the opener and closer tags

Upvotes: 2

Related Questions