Create check box by using the records from MySQL datebase as values

Posted by Shek on June 5, 2008 under PHP | Be the First to Comment | Total View: 11,629 views

Editor’s note: To use the records in the MySQL database as the “values and display text” of the check box is a good idea for the administrator because he/she can add, update or delete check box’s items from the MySQL database, without touching the HTML source.

I have created an example to demonstrate how to do so.

In this example:
I have created a table named “test” in MySQL database and has 2 fields, one named “car” and the other one named “colour” and a few records have inserted into the table.

I have created a PHP file called “createcheckbox.php” and the codes are:

First we have to connect to the database:

<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
?>

Then we start to create a HTML form here:

<form name="aform">
Choose a car's colour:
<br>

Now we create a query to get all the records from the MySQL database table “test”:

<?php
$query = "SELECT * FROM test";
?>

Now we run the query:

<?php
$result = mysql_query($query);
?>

Now we use a while loop and create a check box with every record in the MySQL database table “test”:

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line[car]?>"><?php echo $line[colour]?>
<br>
<?php } ?>
</form>

All together we have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
?>
<form name="aform">
Choose a car's colour:
<br>
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="checkbox" name="car" value="<?php echo $line[car]?>"><?php echo $line[colour]?>
<br>
<?php } ?>
</form>

Not what you want? Try a Search

Add A Comment

*