Karthick Terror
Karthick Terror

Reputation: 821

How to add checkbox value in database?

<?php 
 if(isset($_REQUEST['submit']))
 {
        $category = mysql_real_escape_string(implode(',', $_POST['category']));

 }

$ins=mysql_query("insert into fruits (`category`) values ('$category') " ) ;

?>

<form name="form1" method="post" action="">
<input type="checkbox"    name="category[]" value="apple" >Apple
<input type="checkbox"    name="category[]" value="orange" >Orange
<input type="checkbox"    name="category[]" value="mango" >Mango
<input type="submit" name="submit" value="submit"  />
</form>

I need to save checkbox value like [apple][orange][mango] but now it save like apple,orange,mango

can anyone help me ?

Upvotes: 2

Views: 3053

Answers (3)

totallyNotLizards
totallyNotLizards

Reputation: 8569

I agree with Quentin's comment on your question - many to many with bridge table is the best way to go for this, I've had to do something very similar recently and that was the best solution.

If you are intent on doing this anyway, you'd need to just loop through the category[] array and build a string with your square brackets, something like this:

$str='';
foreach ($_POST['category'] as $val)
{
    $str.='['.$val.']';
}

Unless I've misunderstood the significance of the brackets that is :)

EDIT: Just read http://bobby-tables.com/, (courtesy of quentin) lmao. you should consider the possible security implications before going ahead with this.

Upvotes: 2

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

Not sure I've understood you right, but try this

$category = mysql_real_escape_string(implode('][', $_POST['category']));
if($category)
   $category='['.$category.']';

I hope it will be helpfull.

Upvotes: 0

Nick Pavluk
Nick Pavluk

Reputation: 379

Use cycle to create string you need

$category = '';

foreach ( $_POST['category'] as $cat )
{
    $category .= '[' . $cat . ']';
}

$ins=mysql_query("insert into fruits (`category`) values ('$category') " ) ;

Upvotes: 2

Related Questions