Storing Multiple Checkbox Data in MySQL Database with PHP
Asked Answered
H

4

5

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.

Hennery answered 5/3, 2012 at 2:52 Comment(5)
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.Feoffee
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.Sheilasheilah
php.net/manual/en/function.implode.php php.net/manual/en/function.explode.phpShepp
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.Hennery
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 commentsRattray
D
15

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

Doctor answered 5/3, 2012 at 3:0 Comment(1)
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.Hennery
P
2

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";
}
Propaedeutic answered 29/11, 2012 at 10:41 Comment(1)
please take a bit more care of your code formatting, otherwise it's hard to read :-)Clerical
H
1

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);
Hairline answered 5/3, 2012 at 3:7 Comment(0)
N
-1

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.

Neaten answered 5/3, 2012 at 3:15 Comment(2)
-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.Colwin
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.Neaten

© 2022 - 2024 — McMap. All rights reserved.