Forum Moderators: coopster

Message Too Old, No Replies

Inserting checkbox array into database

Checkbox arrays

         

hsmom314

4:15 pm on Apr 4, 2008 (gmt 0)

10+ Year Member



I am attempting to create an HTML form in PHP with checkboxes that dynamically populate based on the database records (this part works fine in the code below) and insert new records when submit is pressed (this part of the code is not working). Once the checkboxes are checked and submit is pressed, I would like to insert records into the database for each checkbox that is checked. In other words, each checkbox that is checked will be a separate record in the database - so if this user selects 3 checkboxes, the code will insert 3 new records. I am very new to PHP and the code below is from a tutorial that I found and the database does not update with the selected checkboxes. Since I can't seem to find any books on this type of programming, I am trying to learn how to do this by exploring sample code but I'm lost. Any help would be greatly appreciated. Thanks! Debbie

<?php

/* insert code to connect to your database here */
// Connect to the db.
/* get the checkbox labels */
$skills = get_checkbox_labels("const_skills");

/* create the html code for a formatted set of
checkboxes */
$html_skills = make_checkbox_html($skills, 3, 400, "skills[]");

?>

<html>
<body>
<br>
<form name="skills" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Check off your web development skills:
<? echo "$html_skills"; ?>
<br>
<input type="submit" value="Submit">
</form>
<pre>
<?php if ($_POST) {print_r($_POST);} ?>
</pre>
</body>
</html>
<?php

function get_checkbox_labels($table_name) {

/* make an array */
$arr = array();

/* construct the query */
$query = "SELECT * FROM $table_name";

/* execute the query */
$qid = mysql_query($query);

/* each row in the result set will be packaged as
an object and put in an array */
while($row= mysql_fetch_object($qid)) {
array_push($arr, $row);
}

return $arr;
}

/* Prints a nicely formatted table of checkbox choices.

$arr is an array of objects that contain the choices
$num is the number of elements wide we display in the table
$width is the value of the width parameter to the table tag
$name is the name of the checkbox array
$checked is an array of element names that should be checked
*/

function make_checkbox_html($arr, $num, $width, $name) {

/* create string to hold out html */
$str = "";

/* make it */
$str .= "<table width=\"$width\" border=\"0\">\n";
$str .= "<tr>\n";

/* determine if we will have to close add
a closing tr tag at the end of our table */
if (count($arr) % $num != 0) {
$closingTR = true;
}

$i = 1;
if (isset($checked)) {
/* if we passed in an array of the checkboxes we want
to be displayed as checked */
foreach ($arr as $ele) {
$str .= "<td><input type=\"checkbox\" name=\"$name\" value=\"$ele->id\"";
foreach ($checked as $entry) {
if ($entry == $ele->value) {
$str .= "checked";
continue;
}
}
$str .= ">";
$str .= "$ele->value";

if ($i % $num == 0) {
$str .= "</tr>\n<tr>";
} else {
$str .= "</td>\n";
}
$i++;
}

} else {
/* we just want to print the checkboxes. none will have checks */
foreach ($arr as $ele) {
$str .= "<td><input type=\"checkbox\" name=\"$name\" value=\"$ele->id\">";
$str .= "$ele->value";

if ($i % $num == 0) {
$str .= "</tr>\n<tr>";
} else {
$str .= "</td>\n";
}
$i++;
}

}

/* tack on a closing tr tag if necessary */
if ($closingTR == true) {
$str .= "</tr></table>\n";
} else {
$str .= "</table>\n";
}

return $str;
}

?>

<?php

/* the function we call to insert.
the $skills argument is the skills array that
is sent to the script when the user hits the submit button
*/
function insert_skills($uid, $skills) {

/* first, we'll delete any entries this user already has
in the table */
purge_lookup("lookup_skills", $uid);

/* now create the sql insert query */
$query = create_checkbox_query($skills, "lookup_skills", $uid);

/* execute the query */
mysql_query($query);
}

/* helper function for insert_skills().
removes all rows in $table with $uid */
function purge_lookup($table, $uid) {
$q = "DELETE FROM $table, WHERE uid = '$uid'";
mysql_query($q);
}

/* helper function for insert_skills().
generates the sctual SQL query */
function create_checkbox_query($arr, $table, $uid) {
$q = "INSERT INTO $table (uid, skill_id) VALUES";

foreach ($arr as $check) {
$q .= " ( $uid , $check )" . ",";
}

/* remove the last comma and return */
return substr($q, 0, -1);
}

?>

bilenkyj

4:26 pm on Apr 4, 2008 (gmt 0)

10+ Year Member



the trick is changing the name of each check box with the use of a counter as the form is being populated based on what is in the database. The user the value of each check box as an array

<input type = "checkbox" name ="thearray[]" value="whatever">
<input type = "checkbox" name ="user[]" value="whatever">
<input type = "checkbox" name ="ipid[]" value="whatever">
<input type = "checkbox" name ="company_name[]" value="whatever">

The array will grow as the from is generated, then you can use the following to recall the array contents

echo"".$_POST['thearray'][$counter]." ".$_POST['user'][$counter]." ".$_POST['ipid'][$counter]." ".$_POST['company_name'][$counter];

- counter is used to cycle through the array, its a bit scrappy but if you have primary keys in place you wont end up updating the wrong table rows if updating is what you want to do

hsmom314

6:07 pm on Apr 4, 2008 (gmt 0)

10+ Year Member



I think I may not have been clear enough in my original post. The code that I've attached has 6 checkboxes of the same array. When any of these are checked, it should add a new record to the database for each box that is checked.

coopster

7:23 pm on Apr 5, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, Debbie.

Although the

insert_skills()
function is defined, you never execute it therefore your INSERT will not occur:


/* the function we call to insert.
the $skills argument is the skills array that
is sent to the script when the user hits the submit button
*/
function insert_skills($uid, $skills) {
...

If I have functions embedded in my script I tend to group them at the top of my code. You don't have to do things this way, but it does two things for me ... first it insures they are defined before I attempt to use them, and second, it makes them easy to find when you are coding. So, if you were to move the functions to the top you could then call the insertion function before you build and output your HTML if the form has already been displayed and the user has submitted information. Something along these lines ...

$uid = 0; // you need to get your $uid variable populated! 
if (isset($_POST['skills'])) { // <- name of your "skills" <input>
$skills = $_POST['skills'];
// you may want to scrub this input first to
// to make sure it contains what you expect!
insert_skills($uid, $skills);
}

Lastly, I would at the very least use mysql_real_escape_string [php.net] before using any user-defined information in an SQL query!
/* helper function for insert_skills(). 
generates the sctual SQL query */
function create_checkbox_query($arr, $table, $uid) {
$q = "INSERT INTO $table (uid, skill_id) VALUES";
foreach ($arr as $check) {
$check = mysql_real_escape_string($check);
$q .= " ( $uid , $check )" . ",";
}
/* remove the last comma and return */
return substr($q, 0, -1);
}

hsmom314

4:33 am on Apr 9, 2008 (gmt 0)

10+ Year Member



Thank you so much for your help. Your suggestions worked. Debbie