0

How can I save the data that was checked in the check boxes and will be inserted to one row in the database? For example the user clicks the two check boxes (Red and Blue). When the save button is clicked, the values of Red and Blue will be save to one row (Colors) in the Products table.

This is my html code

<form action="" method="post">
        <h3>Colors:</h3>
        <input type="checkbox" name="checkbox1" value="White"> White </br>
        <input type="checkbox" name="checkbox2" value="Red"> Red </br>
        <input type="checkbox" name="checkbox3" value="Blue"> Blue </br>
        <input type="checkbox" name="checkbox4" value="Green"> Green </br>

        <input type="submit" name="save">
</form>

Table Name: Products

Columns: Product_name, Colors

Ejardy
  • 101
  • 1
  • 4
  • 14
  • i suggest don't save a comma separated value on `colors` row – Kevin Sep 05 '14 at 05:58
  • [Is storing a delimited list in a database column really that bad?](https://stackoverflow.com/q/3653462/2943403) Also, there is no benefit in repeating the option's text value as the `value` attribute -- just remove the `value` declaration entirely. – mickmackusa Dec 09 '21 at 07:49

1 Answers1

1
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$Colors = implode(',',$_REQUEST['colors']);
$sql = "INSERT INTO Products (Colors) VALUES ('$Colors') ";
mysql_query($sql);
}   
?>

<form action="" method="post">
    <h3>Colors:</h3>
    <input type="checkbox" name = "colors[]" value="White"> White </br>
    <input type="checkbox" name="colors[]" value="Red"> Red </br>
    <input type="checkbox" name="colors[]" value="Blue"> Blue </br>
    <input type="checkbox" name="colors[]" value="Green"> Green </br>

    <input type="submit" name="save">
</form>

The above would save comma seperated Color values in column Colors from Products table.

Pundit
  • 229
  • 2
  • 7
  • Another alternative would be `json_encode`, especially if the data might have a comma in it. psst PDO, SQL injection. – MrYellow Sep 05 '14 at 06:24
  • Thanks! The variable name must be the same but if will have a different when it comes to []. What does implode do? – Ejardy Sep 05 '14 at 09:20