Infolinks

Breaking

Adsense

Wednesday, September 14, 2016

How To Create A Database-Driven Checkbox Using PHP and MySQL

Checkbox is allows multiple selection of values from checkboxes of same type which is the opposite of radio button which allows single selection only from a certain type.

Some checkboxes reuires a simple html encoding for lesser options. But there are some that requires a database-driven checkboxes to easily implement it.

So today I am going to share to you on how to create a database-driven checkbox using PHP and MySQL. The following sample code will look like on the image below.

Here are the table structure and the sample data. By the way, sample is the database name.

Table structure for browser table

CREATE TABLE `browser` (
`browser_id` int(11) NOT NULL,
`browser_name` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert Record in browser table

INSERT INTO `browser` (`browser_id`, `browser_name`) VALUES
(1, 'Mozilla Firefox'),
(2, 'Microsoft Edge'),
(3, 'Google Chrome'),
(4, 'Sarafi');

The function of the below code is to display checkboxes whose values contains the browser id and browser name serves as the label for each checkboxes.

Database-Driven Checkbox Code

<!DOCTYPE html>
<html>
<head>
<title>Used Browser</title>
</head>
<body>
<h3>Choose the browser that you use.</h3>
<?php
//database connection
$con = mysqli_connect("localhost","root","","sample");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//display a database-driven checkbox
$query=mysqli_query($con,"select * from browser order by browser_name")or die(mysqli_error());
while($row=mysqli_fetch_array($query)){
$id=$row['browser_id'];
$name=$row['browser_name'];

?>
<input type="checkbox" name="browser[]" value="<?php echo $id;?>"><?php echo $name;?>
<?php }?>

</body>
</html>

Hope this helps. ^_^

How To Create A Database-Driven Checkbox Using PHP and MySQL

1 comment:

Adbox