How to Dynamically Get the Value of a Select Tag from MySQL Table Using PHP

Language

This tutorial will help you on how to dynamically get the value of a select tag from MySQL Table using PHP. This tutorial will not teach you on how to create a good design but rather to give you knowledge on how to create a fully functional select tag.

Creating our Database

First, we're going to create a database that contains the data that we want to show as options in our select tag. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as "select". 3. After creating a database, click the SQL and paste the below code. See image below for detailed instruction.
  1. CREATE TABLE `user` (
  2. `userid` INT(11) NOT NULL AUTO_INCREMENT,
  3. `uname` VARCHAR(50) NOT NULL,
  4. PRIMARY KEY (`userid`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
select

Inserting Data into our Database

Next, we insert data into our database. These are the data that we are going to show in out option. 1. Click our database "select". 2. Click SQL and paste the below code.
  1. INSERT INTO `user` (`uname`) VALUES
  2. ('neovic'),
  3. ('leeann');

Creating our Connection

Next step is to create a database connection and save it as "conn.php". This file will serve as our bridge between our page and our database. To create the file, open your HTML code editor and paste the code below after the tag.
  1. <?php
  2. $conn = mysqli_connect("localhost","root","","select");
  3.  
  4. // Check connection
  5. {
  6. echo "Failed to connect to MySQL: " . mysqli_connect_error();
  7. }
  8. ?>

Creating our Select Tag

Lastly, we create our page to show our select tag and name it as "index.php". This page will show the select tag where options are data from our database. To create the page, open your HTML code editor and paste the code below after the tag.
  1. <!DOCTYPE html>
  2. <title>Dynamically Get the Value of a Select Tag from MySQL Table Using PHP</title>
  3. </head>
  4. <h2>Who's Handsome?</h2>
  5. <?php
  6. include('conn.php');
  7. $query=mysqli_query($conn,"select * from `user`");
  8. while($row=mysqli_fetch_array($query)){
  9. ?>
  10. <option><?php echo $row['uname']; ?></option>
  11. <?php
  12. }
  13. ?>
  14. </select>
  15. </body>
  16. </html>

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment