PHPBuilder - Storing Checkbox Data in a Database Page 4



RSS Twitter
Articles Databases

Storing Checkbox Data in a Database - Page 4

by: Dan LaFlamme
|
October 15, 2000

Inserting into lookup_skills

Now that we have the code to create the form, we need to be able to store the skills that the user checks off. In the make_checkbox_html function above, we called the name of each checkbox element skills[]. The "[]" specify that we will get access to the checked elements in an array. So, all we have to do is run through the array and insert rows into the lookup_skills table. If the person filling out the form clicks 5 skills, we insert 5 rows into the lookup_skills table. Remember that each row in the lookup_skills table has a user id number and a skill number. In the example of the site I gave, users log in and then they can create/edit their profile. You would probably register their userid number as a session variable when they log in, but how you manage userids is beyond the scope of this article. In the code below, we will just assume that we have access to the userid in a variable called $uid. So here are some functions to do the insert:

<?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($q0, -1);
}

?>
That is pretty much all there is to inserting. You now know how to create your form easily by reading from your const_skills table and you also know how to store the users skill selections by simply inserting rows into the lookup_skills table. So now what do you do? Lets look at how to search.

« Previous Page
1
|
2
|
3
|
4
|
5
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Dan LaFlamme

Comment:



Comment:

(Maximum characters: 1200). You have characters left.