Dynamically Get the Value of a Select Tag from MySQL Table PHP Script


Dynamically Get the Value of a Select Tag from MySQL Table PHP Script

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.

 

CREATE TABLE `user` (
`userid` INT(11) NOT NULL AUTO_INCREMENT,
`uname` VARCHAR(50) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

 

 

 

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.

 

INSERT INTO `user` (`uname`) VALUES
('neovic'),
('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.

 

<?php
$conn = mysqli_connect("localhost","root","","select");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

 

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.

 

<!DOCTYPE html>
<html>
<head>
<title>Dynamically Get the Value of a Select Tag from MySQL Table Using PHP</title>
</head>
<body>
<h2>Who's Handsome?</h2>
<select>
<option></option>
<?php
include('conn.php');
$query=mysqli_query($conn,"select * from `user`");
while($row=mysqli_fetch_array($query)){
?>
<option><?php echo $row['uname']; ?></option>
<?php
}
?>
</select>
</body>
</html>

 

 

Read Me

 



Find More Dynamically Get the Value of a Select Tag from MySQL Table PHP Script

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories