Hello,


I have this multiple checklist and I cannot figure out how to enter the checked values into the database.

The table is called "colors" and the column name is "color" and is of type "text".

add_color.php

<?php

// connect to database
require "mysql_connect.php";

?>

<?php

// get value from the form
$color = $_POST['color'];

// add it to the database
$sql_query = ("INSERT INTO colors (color) VALUES ($color)");

?>



<form action="add_color.php" method="post" enctype="multipart/form-data" name="colorform" id="colorform">

<input type="checkbox" name="color[]" value="black" /> Black
<input type="checkbox" name="color[]" value="red" /> Red
<input type="checkbox" name="color[]" value="blue" /> Blue
<input type="checkbox" name="color[]" value="white" /> White

<td><input name="submit" type="submit" value="Add color" />

</form>

I am new to php and sql and I have searched a lot on the internet buy just cannot figure out how to get this to work. Please help me to get this working.

Thanks

1) $_POST is an array, so you should use foreach.
2) You generate $sql_query (a string), but it is never executed (using mysql_query)

Ah that makes sense. So the following would work?

<?php

// connect to database
require "mysql_connect.php";

?>

<?php

// get value from the form
$color = $_POST['color'];

foreach($_POST['color'] as $colors){
$insert = mysql_query("INSERT INTO $colors (color) VALUES ($color)");
}


<form action="add_color.php" method="post" enctype="multipart/form-data" name="colorform" id="colorform">

<input type="checkbox" name="color[]" value="black" /> Black
<input type="checkbox" name="color[]" value="red" /> Red
<input type="checkbox" name="color[]" value="blue" /> Blue
<input type="checkbox" name="color[]" value="white" /> White

<td><input name="submit" type="submit" value="Add color" />

</form>

Minor fix:

$colors = $_POST['color'];
foreach ($colors as $color) {
  $insert = mysql_query("INSERT INTO colors (color) VALUES ('$color')");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.