1,105,208 Community Members

multiple checklist sql insert

Member Avatar
shamed
Newbie Poster
2 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
pritaeas
mod_pritaeas
11,296 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,832 [?]
Skill Endorsements: 155 [?]
Moderator
Featured
Sponsor
 
0
 

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)

Member Avatar
shamed
Newbie Poster
2 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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>
Member Avatar
pritaeas
mod_pritaeas
11,296 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,832 [?]
Skill Endorsements: 155 [?]
Moderator
Featured
Sponsor
 
0
 

Minor fix:

$colors = $_POST['color'];
foreach ($colors as $color) {
  $insert = mysql_query("INSERT INTO colors (color) VALUES ('$color')");
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: