Sep
2
Insert Checkbox Values to MySQL Using PHP
September 2, 2008 |
This article teaches you how to insert HTML form checkbox values into MySQL database as a string of comma separated values using PHP.
First you need to give the series of checkboxes a same name with [] behind the name, in your form:
<?
if (!isset($_POST['submit'])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="checkbox" name="media[]" value="Poster" />Poster<br />
<input type="checkbox" name="media[]" value="Website" />Website<br />
<input type="checkbox" name="media[]" value="Magazine" />Magazine<br />
<input type="submit" value="submit" name="submit">
</form>
<?
} else {
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$media_array = $_POST['media'];
foreach ($media_array as $one_media) {
$source .= $one_media.", ";
}
$media = substr($source, 0, -2);
$query = "INSERT INTO mydb (media_type)
VALUES( '$media')";
$result = mysql_query($query);
}
?>
</body>
</html>
Now you should have a list of values in comma seperated format in your MySQL database. Hope this helps!
Similar Posts
Comments
8 Comments so far



































[...] Original post by admin [...]
[...] Original post by admin [...]
Hi, this is really an useful tutorial. thanks for sharing!
dear sir,
i have a problem.
the value inserted on bd is word “array” and not my checked values.
Hi vinicius,
What’s the exact code you use?
Thank you heaps, this code worked perfectly!!!!!
if the checkbox is checked,how can i insert the value in database using php
Looks great. One question.
How would I insert 2 other fields into the db for every $media entry?
For example. If user1 selected 4 checkboxes from friend2, how would you put:
user1 $media[1] friend2
user1 $media[2] friend2
.
.
Thanks,
Neil