Create a text file with your text editor. Save the file as "drop-down-menu-populate.php."
Type, beginning at the first line of the text editor, the PHP code that will indicate the start of the PHP script and make the connection between the PHP code and the MySQL database that the PHP code is to connect to. Include in the code a PHP conditional statement to display an error message if the connection failed and to create a database table (called test11) and to store the dress sizes (3, 5 and 10) in the test11 database table if the connection succeeded.
<?php
$mysqli = mysqli_connect("localhost", "username", "password", "databasename");
if (mysqli_connect_errno()) {
printf("Failed to connect to server's mysql database : %s\n", mysqli_connect_error());
exit();
} else {
$sql = "CREATE TABLE dresses (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, sizes INT)";
$res = mysqli_query($mysqli, $sql);
$sql1 = "INSERT INTO dresses (sizes) VALUES ('3')";
$res1 = mysqli_query($mysqli, $sql1);
$sql2 = "INSERT INTO dresses (sizes) VALUES ('5')";
$res2 = mysqli_query($mysqli, $sql2);
$sql3 = "INSERT INTO dresses (sizes) VALUES ('10')";
$res3 = mysqli_query($mysqli, $sql3);
Type in the text editor, starting on the next line, the PHP code that will retrieve all the dress sizes from the dresses table. Include in the code the HTML markup tags to generate the drop-down menu (list box).
$query="SELECT sizes ,id FROM dresses";
$result = mysqli_query ($mysqli, $query);
echo "<select size=sizes value=''>Dress Sizes Available</option>";
while($dress1=mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<option value=$dress1[id]>$dress1[sizes]</option>";
}
echo "</select>";
mysqli_close($mysqli);
}
?>
The code generates a query to retrieve the contents of the id and sizes fields from the dresses database table. The text in quotation marks in the "echo" functions are used to display the list box, specifically to output the HTML list tag and the option tag used to specify the different menu items in the list. The "while" statement is used in conjunction with the "mysqli_fetch_array" function and the HTML markup in the "echo" statement to populate the list box with the dress sizes in the "dresses" database table.