Forum Moderators: coopster

Message Too Old, No Replies

Storing form array data to MySQL using PHP

         

osemollie

11:21 am on Feb 2, 2006 (gmt 0)

10+ Year Member



Let's say you've got a form with check boxes like below:
<form method="post" action="path to script">
<input type="checkbox" id="colors[]" value="red" /> Red
<input type="checkbox" id="colors[]" value="blue" /> Blue
<input type="checkbox" id="colors[]" value="green" /> Green
<input type="checkbox" id="colors[]" value="yellow" /> Yellow
</form>

How can I save this data into mySQL and how can I view these data from DB?

tomda

11:40 am on Feb 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is how I am doing it. Hope it is the correct way and that I am not misleading you ;)


// FUNCTION
function check1($var){if(!preg_match("/[^A-Za-z]/",$var)) {return TRUE;} else {return FALSE;}}

// CHECK POST VALUE EXIST
if(isset($_POST["colors"])) {$colors=$_POST["colors"];
// IF YES, COUNT ARRAY
$nb_colors=count($colors);
// MAKE SURE THAT EVERY VALUE OF THE ARRAY IS [a-z]
for ($i="0"; $i<$nb_colors; $i++) {
if(!check1($colors[$i])) {$colors[$i]="";}} unset($nb_colors);}
// IF NOT, ARRAY NULL
else {$colors=array();}

OK, you have your array checked and safe for SQL, you can implode the array for insertion in your database


$colors = implode("-", $colors);
$sql = "INSERT INTO $db (`db_id`,`colors`) VALUES (NULL,'$coche')";