Sep

2

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

Name (required)

Email (required)

Website

Speak your mind

8 Comments so far

  1. Insert Checkbox Values to MySQL Using PHP : insuranceslowprices on September 2, 2008 9:19 am

    [...] Original post by admin [...]

  2. Insert Checkbox Values to MySQL Using PHP on September 2, 2008 10:42 am

    [...] Original post by admin [...]

  3. Aletheya on September 3, 2008 9:49 am

    Hi, this is really an useful tutorial. thanks for sharing!

  4. vinicius(brasilian) on October 13, 2008 3:21 pm

    dear sir,

    i have a problem.
    the value inserted on bd is word “array” and not my checked values.

  5. admin on October 14, 2008 7:11 am

    Hi vinicius,

    What’s the exact code you use?

  6. Stefanie on October 21, 2008 9:44 pm

    Thank you heaps, this code worked perfectly!!!!!

  7. Mythili on December 9, 2008 1:28 am

    if the checkbox is checked,how can i insert the value in database using php

  8. Neil on December 10, 2008 3:22 pm

    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

Sponsors




Links