Storing Multiple Checkbox Data in Mysql Database With PHP: 4 Answers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Storing Multiple Checkbox Data in MySQL Database with PHP Ask Question

I want to have multiple checkbox values be stored into one field in a database. (Ex. 1, 24,56,100). I am wanting to know how I can make this happen, and
how does PHP read these values from the database if I want to call variables in a query?

Basically I am creating a blog app (for fun and experience) and I want the user to be able to change the visibility of each blog post through checkboxes. I
know you are probably thinking why don't I just have a visibility field for each blog post. I understand why it is not recommended to do this, but I can't think of
any other way to do this. To explain a bit more: I want to attach this application to a CMS I have already built, and basically I have a table with blog posts, and
then I want the user to be able to go to different pages within their site and add a blog. Well, what if the user wants to use the same blog on 3 different pages,
but only wants certain posts to show on each page. So this is why I am confused right now.

php mysql denormalized

edited Mar 5 '12 at 3:50 asked Mar 5 '12 at 2:52


Charles drummer392
43.9k 11 81 121 125 2 5 31

1 You're asking to store denormalized data, which isn't recommended. If you want to extract any information on the checkbox values, it will be a lot of effort that could be avoided. –
OMG Ponies Mar 5 '12 at 2:55

2 It is unwise to store multiple values in one column. Instead create a normalized table with two columns - a foreign key to the post id, and a checkbox value. Duplicate post ids are
allowed in that table. – Michael Berkowski Mar 5 '12 at 2:56

php.net/manual/en/function.implode.php php.net/manual/en/function.explode.php – Stephen Bugs Kamenar Mar 5 '12 at 2:56

I understand why it is not recommended to do this, but I can't think of any other way to do this. To explain a bit more: I want to attach this application to a CMS I have already
built, and basically I have a table with blog posts, and then I want the user to be able to go to different pages within their site and add a blog. Well, what if the user wants to use
the same blog on 3 different pages, but only wants certain posts to show on each page. So this is why I am confused right now. – drummer392 Mar 5 '12 at 3:34

I know your question has already been answered, but regarding the issue you refer to in the above comment, you could simply create a table that has postID+pageID as foreign
keys, and this will keep the values of post,page so that you can show certain posts only in certain pages. (the table is not required to have a primary key but in anycase you can
have an autoincrement temporary id column). Thi way you can have the mapping for post/page. I believe this is what OMG Ponies and Michael Berkwoski recommended to you
in their comments – George May 17 '15 at 9:31

4 Answers

Even though I am not in favor of saving data like that but here is what you can do, if you really want to
do it that way. I suggest you have a denormalized table and store your vals there

in your HTML you can have your checkboxes like this (considering you are storing ids of some sort)

<input type="checkbox" name="ids[]" value"1" />


<input type="checkbox" name="ids[]" value"24" />
<input type="checkbox" name="ids[]" value"56" />
<input type="checkbox" name="ids[]" value"100" />

On you php side you can use function implode to form ids into a string as shown below (considering
you are doing a POST)

$ids = implode(",",$_POST["ids"]);

Where you read from the database you can transform the value from db to an array like this

$ids_array = explode(",",$row->ids);

I hope this helps

answered Mar 5 '12 at 3:00


Jaspreet Chahal
2,520 1 10 17

I think this will work! I understand why it is not recommended to do this, but I can't think of any other way to do this.
To explain a bit more: I want to attach this application to a CMS I have already built, and basically I have a table with
blog posts, and then I want the user to be able to go to different pages within their site and add a blog. Well, what if
the user wants to use the same blog on 3 different pages, but only wants certain posts to show on each page. So
this is why I am confused right now. – drummer392 Mar 5 '12 at 3:31

first create database:

create table employee(id int(10) not null, name varchar(20), hobbie varchar(20),
worked varchar(20), primary key(id));

after that create an html page like that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<body background="blue">
<form action="check.php" method="post">
Name: <input name="Name" type="text" id="Name" /><br />
<br />
<br />
Which you do you want to likes?<br />
<input type="checkbox" name="Hobbies[]" value="Books" />Books<br />
<input type="checkbox" name="Hobbies[]" value="Movies" />Movies<br />
<input type="checkbox" name="Hobbies[]" value="Sports" />Sports<br />
<input type="checkbox" name="Hobbies[]" value="Games" />Games<br />
<input type="checkbox" name="Hobbies[]" value="Travelling" />Travelling<br />

worked: <input name="Worked" type="text" id="Worked" /><br />


<br />

<input type="submit" name="submit" value="Submit" />


<input type="reset" name="reset" value="reset" />

</form>
</body>
</html>

after that we have do mysql connect.php

<?php
$server="localhost";
$user="root";
$password="";
$database="empcheckbox";

$link=mysql_connect($server,$user,$password) or die("the connection is terminated please


check me!".mysql_error());
mysql_select_db($database,$link);
?>

after that we have to create an check.php like that ok

<?php

if(isset($_POST['submit']))
{
$name=mysql_real_escape_string($_POST['Name']);
$worked=mysql_real_escape_string($_POST['Worked']);
$hobb= $_POST['Hobbies'];
if(empty($hobb))
{
echo("<p>You didn't select any any hobby.</p>\n");
}
else
{
$N = count($hobb);
echo("<p>You selected $N Hobbies(s): ");
for($i=0; $i < $N; $i++)
{
$var1=$hobb[$i];
include ('connect.php');
$table = "INSERT INTO employee (name, hobbies, worked) ".
"VALUES ('$name', '$var1', '$worked')";
mysql_query($table) or die(mysql_error());
$inserted_fid = mysql_insert_id();
mysql_close();
}

echo "successfully uploaded!..";


}
}
else
{
echo "error please check ur code";
}

edited Nov 29 '12 at 10:52 answered Nov 29 '12 at 10:41


kleopatra sri
43k 16 69 147 21 1

3 please take a bit more care of your code formatting, otherwise it's hard to read :-) – kleopatra Nov 29 '12 at 10:54

The perfect solution for this is task the creation of normalized table as commented by @OMG and
@Michael.

But here is the answer for what you just asked

$ids = implode(", ", $_POST['ids']);

Store this in MySQL table. You can use LIKE command to query the table and use the explode to get
back the ids in array.

$query = "SELECT * FROM <table> WHERE ids LIKE '%,2, %'"; // get posts having id 2

$id = explode(", ", $result->ids);

Join Stack Overflow to learn, share knowledge, and build your career. Email Sign Up OR SIGN IN WITH Google Facebook
edited Sep 14 '16 at 10:18 answered Mar 5 '12 at 3:07
Rohan Kumar Alex Jose
33.4k 9 52 84 265 3 16

You're going to want to go through the basics of PHP and MySQL.

Check out tizag.com or w3schools.com, or some other sites (the tutorials are plentiful).

Here's the basics though--and remember this, as it'll help you in your understanding.

MySQL is a database. A database is typically used for storing data. PHP is a programming language.
It's typically used for programming.

So, some wonderful developers out there have already taken care of the steps for talking to the
database from PHP. All you have to do is establish a connection.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else { echo "Connection made"; }
?>

See mysql_connect via W3Schools

Okay, so what you have done here, is you've connected to the database SERVER. You haven't
selected a database yet. Think of it like going to a movie theater, you still have to pick a movie to
watch.

So, now we connect to our database:

mysql_select_db("my_db", $con); //Notice we're using our connection, "$con"

See mysql_select_db via W3Schools

Once you've connected to your database, you're ready to grab some information from it.
To do this, you need to create your SQL query.

Something to the tune of:

$sql = "SELECT article_id FROM user_view_blog_posts WHERE user_id = '$user_id'";

See the SELECT statement via W3Schools

Depending on how your table is set up, that will get you the list for the current user. I'm assuming that
you already have the user's id (or a way to get it), since they have the ability to define their own
preferences for the site.

Now that you have the SQL query to get the articles, you need to query the database.

$result = mysql_query($sql);
// Now, get the data
while($row = mysql_fetch_array($result)) {
$articles[] = $row['article_id'];
}

That should get you your list of ID's that you need.

I'll let you figure out the rest. It's pretty straight-forward, and you've got all of the tools that you need
now. The only thing you might want to brush up on is explode and foreach .

So, the way you store them is up to you. Look into explode for splitting them up when they're stored
that way.

answered Mar 5 '12 at 3:15


Tim
2,756 3 15 39

1 -1, w3schools' PHP material is of horrifying quality. They each poor practices. Their examples are rife with SQL
injection and cross-site scripting vulnerabilities. Do not recommend them under any circumstances. – Charles Mar
5 '12 at 3:52

I don't think it should be taken as gospel, but they explain the basics. What a beginner needs to get up and running
is functionality. And as they grow you introduce other concepts to them. That way you don't over-whelm the person
who is learning. There are plenty of resources out there for security and hardening. And I will continue to
recommend them. – Tim Mar 5 '12 at 4:55

You might also like