如何在数据库中添加复选框值?

问题描述:

<?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 ?

 &lt;?php 
 if(isset($ _ REQUEST ['submit']))
  {
 $ category = mysql_real_escape_string(implode(',',$ _POST ['category'])); 
 
} 
 
 $ ins = mysql_query(“insert into fruits(`category`)values('  $ category')“); 
 
?&gt; 
 
&lt; form name =”form1“method =”post“action =”“&gt; 
&lt; input type =”checkbox“name =”category [  ]“value =”apple“&gt; Apple 
&lt; input type =”checkbox“name =”category []“value =”orange“&gt; Orange 
&lt; input type =”checkbox“name =”category []“  value =“mango”&gt; Mango 
&lt; input type =“submit”name =“submit”value =“submit”/&gt; 
&lt; / form&gt; 
  code>  pre> 
 
  

我需要像[苹果] [橙色] [芒果]一样保存复选框值,但是现在它像苹果,橙子,芒果一样保存 p>

任何人都可以帮助我吗? p> \ n div>

Use cycle to create string you need

$category = '';

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

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

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.

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.