Alright, So i am trying to code a little PHP Search Script for My website so users can simply do a search from a artist name, song name or a city.
My table in my database has 'city', 'artist' and 'city'.
Here is my form:
<div id="search">
<form name="search" method="post" action="../searchDb.php">
<input type="text" name="find" placeholder="What are we searching for ?"/> in
<Select NAME="field">
<Option VALUE="artist">Artist</option>
<Option VALUE="song">Song</option>
<Option VALUE="city">City</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</div>
As you can see, there are three OPTION values (one for each column in my table).
Here is my PHP code:
<?php
$searching = "searching";
$find = "find";
$field = "field";
//this is to make sure the user entered content
if ($searching =="yes")
{
echo "<p><h2>Results</h2></p>";
//if user did not enter anything in the search box, give error
if ($find == "")
{
echo "<p>You forgot to enter a search term</p>";
}
include 'connect.php';
// strip whitespace, non case sensitive
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//perform search in specified field
$data = mysql_query("SELECT * FROM artists_table WHERE upper($field) LIKE'%$find%'");
//show results
while($result = mysql_fetch_array( $data ))
{
echo $result['artist'];
echo " ";
echo $result['song'];
echo "<br>";
echo $result['city'];
echo "<br>";
echo "<br>";
}
//counts results. ifnone. error
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//show user what he searched.
echo "<b>Searched For:</b> " .$find;
}
?>
My connect.php (that is included) works perfectly (i have that same file working on another page, no problems..So its safe to say thats not the problem).
When i do a test and run a search, it loads up my searchDb.php but NOTHING is displayed. Simply a white page...
Any help would be greatly appreciated. I am lost as to why or what is not working...
Thanks Guys !
If this is your code, then you are hardcoding $searching = "searching", but in your if you are checking if $searching =="yes", so none of the code will show.
<?php
$searching = "searching";
...
...
//this is to make sure the user entered content
if ($searching =="yes")
{
...
}
Edit-
My guess is that you wanted to do something like-
$searching = mysql_real_escape_string($_POST['searching']); // sanitized just to be consistant.
$find = mysql_real_escape_string($_POST['find']);
$field = mysql_real_escape_string($_POST['field']);
Note- you should not be writing new code with mysql_* functions. You should learn either mysqli_ or PDO - http://php.net/manual/en/mysqlinfo.api.choosing.php
Here are 2 ways to avoid getting the "Notice: Undefined variable"
Check if submit button was pushed
if (isset($_POST['search'])) {
$searching = mysql_real_escape_string($_POST['searching']); // sanitized just to be consistant.
$find = mysql_real_escape_string($_POST['find']);
$field = mysql_real_escape_string($_POST['field']);
}
Or check if each field is set, and set it to the value, and if not set to no/empty
if (isset($_POST['search'])) { // checks to see if the form submit button was pushed
$searching = isset($_POST['search']) ? mysql_real_escape_string($_POST['searching']) : 'no'; // sanitized just to be consistant.
$find = isset($_POST['find']) ? mysql_real_escape_string($_POST['find']) : '';
$field = isset($_POST['field']) ? mysql_real_escape_string($_POST['field']) : '';
}
Related
I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I have a PHP website to display products. I need to introduce a 'Search' feature whereby a keyword or phrase can be found among number of products.
I went through number of existing scripts and wrote/modified one for me which though able to connect to database, doesn't return any value. The debug mode throws a warning " mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ". Seems I am not collecting the query value correctly. The PHP Manuals says that mysqli_query() returns FALSE on failure and for successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object and for other successful queries mysqli_query() will return TRUE ".
Any suggestions?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
# $db = mysqli_connect('localhost','username','password','database' );
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
To do your literal search as you have it, you would need to change the code '%{searchterm}%' to '%$searchterm%', since the brackets aren't needed and you were searching for the phrase "{searchterm}." Outside of that you might want to take a look at FULLTEXT search capabilities since you're doing a literal search in your current method.
To make the output look like Google's output you would simply code a wrapper for each search result and style them with CSS and HTML.
I think it should be something like '%$searchterm%', not '%{searchterm}%' in your query. You are not searching for your variable $searchterm in your example.
Google's display uses LIMIT in the query so it only displays a certain amount of results at a time (known as pagination).
This is tested and works. You will need to change 1) db connection info in the search engine class. 2) If you want it to be on separate pages, you will have to split it up. If not, copy this whole code to one page and it will work on that one page.
<?php
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
class SearchEngine
{
protected $searchterm;
public function execute($searchword)
{
$this->searchterm = htmlentities(trim($searchword), ENT_QUOTES);
}
public function display()
{ ?>
<h1>Results</h1>
<?php
//If they forget to enter a search term display an error
if(empty($this->searchterm)) { ?>
<h3>Search Empty</h3>
<p>You must fill out search field.</p>
<?php }
else {
$con = new DBEngine('localhost','database','username','password');
$results = $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");
if($results !== 0 && !empty($results)) { ?>
<p>Number of match found: <?php echo count($results); ?> on search:<br />
<?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
<?php
foreach($results as $rows) {
echo '<pre>';
print_r($rows);
echo '</pre>';
}
}
else { ?>
<h3>No results found.</h3>
<?php
}
}
}
}
if(isset($_POST['submit'])) {
$searcher = new SearchEngine();
$searcher->execute($_POST['searchterm']);
$searcher->display();
} ?>
<form name="search" method="post" action="">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
I have a site in which logged in users can accumulate points which they can later buy with via a shopping cart. The page below is an admin php feature in which an Admin can give points to an individual user (one user at a time for now).
There are three tables involved with this script:
users: contains the users details
tally_point: stores all of the points transactions, both incoming and ordering
reward_points: stores the total amount of points that the user has
The script retrieves the users’ details via a drop down menu and adds the points to the tally point table ok but....
<?php # add-points-ind.php
// This is the main page for the site.
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Add Points to User';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
?>
<h1>Add Points to User</h1>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php //add-points-ind.php
// This page allows the admin to add points to an individual user
require_once ('mydatabase.php'); // Connect to the database.
if (isset($_POST['submitted'])) { // Check if the form has been submitted.
// Check if points were submitted through the form.
if (is_numeric($_POST['tally_points_in'])) {
$p = (float) $_POST['tally_points_in'];
} else {
$p = FALSE;
echo '<p><font color="red">Please enter the pointås!</font></p>';
}
// Validate the User has been selected
if ($_POST['selected_user'] == 'new') {
// If it's a new categories, add the categories to the database.
$query = 'INSERT INTO tally_points (users_id) VALUES (';
// Check for a last_name.
if (!empty($_POST['users_id'])) {
$query .= "'" . escape_data($_POST['users_id']) . "')";
$result = mysql_query ($query); // Run the query.
$a = mysql_insert_id(); // Get the categories ID.
} else { // No last name value.
$a = FALSE;
echo '<p><font color="red">Please enter the Dealers name!</font></p>';
}
} elseif ( ($_POST['selected_user'] == 'existing') && ($_POST['existing'] > 0))
{ // Existing categories.
$a = (int) $_POST['existing'];
} else { // No categories selected.
$a = FALSE;
echo '<p><font color="red">Please select a registered Dealer!</font></p>';
}
if ($p && $a) { // If everything's OK.
// Add the print to the database.
$query = "INSERT INTO tally_point (users_id, tally_points_in, order_id, total, tally_points_entry_date) VALUES ('$a', '$p', '0', '0', NOW())";
if ($result = mysql_query ($query))
{
// Worked.
echo '<p>The reward product has been added.</p><br />Go back<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
} else {
// If the query did not run OK.
echo '<p><font color="red">Your submission could not be
processed due to a system error.</font></p>';
}
} else { // Failed a test.
echo '<p><font color="red">Please click "back" and try again.</font></p>';
}
} else { // Display the form.
?>
<form enctype="multipart/form-data" action="add-points-ind.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
<fieldset>
<legend>Add Points Individually:</legend>
<p><b>Select User:</b></p>
<p>
<select name="existing"><option>Select One</option>
<?php // Retrieve all the users details and add to the pull-down menu.
$query = "SELECT users_id, users_sale_id, users_first_name, users_surname FROM users ORDER BY users_surname ASC";
$result = #mysql_query ($query);
while ($row = #mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<option value=\"{$row['users_id']}\">{$row['users_sale_id']}: {$row['users_first_name']} {$row['users_surname']} </option>\n";
}
#mysql_close($dbc); // Close the database connection.
?>
</select></p>
<span class="extras"><input type="radio" name="selected_user" value="existing" /> Please confirm this is the correct user</span>
<p><b>Points:</b> <br />
<input type="text" name="tally_points_in" size="10" maxlength="10" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden"name="submitted" value="TRUE" />
</form>
<?php
} // End of main conditional.
?>
<br class="clearboth" />
End text
</div>
<?php // Include the HTML footer file.
include ('includes/footer_admin_user.html');
?>
... Im having trouble with getting the new points added to the points total field (reward_user_points) in the reward_points table, I have some code below but Im not sure where I am supposed to put it, if anyone has any suggestions please let me know.
<?php
$query = "SELECT reward_user_points FROM reward_points WHERE users_id = $a";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$TotalPoints = $row['reward_user_points'];
if (#mysql_affected_rows($dbc) == 1) { // Whohoo!
$new_credit = $TotalPoints + $p;
$query = "UPDATE reward_points SET reward_user_points ='$new_credit' WHERE users_id = $a";
$result = #mysql_query($query);
}
?>
Ok, I have to say that I don't understand very well what your trouble is. You say you're having trouble with getting the new points added to the points total field, but could you be a little more specific? Is there any error message returned by php or mysql?
I want my form input not to act upon an empty search.
I don't want it to even go to the results page and show an error message.
SO
how can I have it so nothing happens when clicking the submit/pressing enter OR pressing space bar then enter?
Can this be done with javascript?
HTML:
<form action="search.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
PHP:
<?php
$conn = mysql_connect("", "", "")
or die (mysql_error());
mysql_select_db("testable");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$term = addcslashes($term,'%_');
$term = "%" . $_POST["term"] . "%";
if (!mysql_select_db("weezycouk_641290_db2")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
**if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "SELECT FName,LName,Phone
FROM testable
WHERE FName LIKE '%". mysql_real_escape_string($term) ."%'";
$result = mysql_query($sql);
}**
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br><br><div class="data1">';
echo htmlentities($row["FName"]);
echo '</div><br><div class="data2">';
echo htmlentities($row["LName"]);
echo '</div><br><div class="data3">';
echo htmlentities($row["Phone"]);
echo '</div>';
}
mysql_free_result($result);
?>
Preventing the form from being submitted via JS is a quick fix, but you still need to handle the possibility that someone could STILL submit a blank search:
if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "...."
blah blah blah
}
note the use of mysql_real_escape_string(). It is THE safe method for strings in mysql queries. addslashes is a hideously broken piece of crap and should NEVER be used for SQL injection prevention.
You can check the length in JS and abort is it's blank
Yes, you can do that using javascript.
Add a javascript function to handle on click event of submit button.
<input type="submit" name="submit" value="Submit" onclick="submitForm(event)" />
Inside that javascript function, check whether textbox is empty or not
function submitForm(event){
var val = document.getElementsByName('term')[0].value;
if (val==null || val.trim()==""){
//document.getElementsByTagName('form')[0].submit();
event.preventDefault();
return false;
}
else {
return true;
}
}
If empty, prevent default event and return false => prevent submission
if not empty, return true => submit the form.
I have a very simple PHP form, which shows a checkbox, and will store if it is checked or not in a database. This works for the initial inserting, but not for updating. I have tested cases where $saleid equals $pk and it does not enter the if branch to update...why?
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"];
else die("Invalid URL");
if (isset($_GET["pk"])) { $pk = $_GET["pk"]; }
$checkfield = "";
$checkboxes = (isset($_POST['checkboxes'])? $_POST['checkboxes'] : array());
if (in_array('field', $checkboxes)) $checkfield = 'checked';
$con = mysqli_connect("localhost","user","", "db");
if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; }
$con->set_charset("utf8");
$getformdata = $con->query("select saleid, field from STATUS where saleid = '$pk'");
$saleid = "";
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
}
if($cmd=="submitinfo") {
if ($saleid == null) {
$statusQuery = "INSERT INTO STATUS VALUES (?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("sssssssssssss", $pk, $checkfield);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
} else if ($saleid == $pk) {
$blah = "what";
$statusQuery = "UPDATE STATUS SET field = ? WHERE saleid = ?";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $checkfield, $pk);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
}
if($cmd=="EditStatusData") {
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
<h1>Editing information for Auction No: ".$pk."</h1>
<input type=\"checkbox\" name=\"checkboxes[]\" value=\"field\" ".$checkfield." />
<label for=\"field\">Test</label>
<br />
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
}
?>
well i created a table and ran your code and it works fine for me
the reason why it doesn't "look" like update is working, is because you are reading
$saleid and $checkfield from the database then building an update statement that puts the same two values back into the database
which probably isn't what you are wanting to do
this line here sets $checkfield to 'checked',
if (in_array('field', $checkboxes)) $checkfield = 'checked';
then you set $checkfield from the database (overwriting the value 'checked' )
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
then you write the original value of checkfield back to the database
$statusInfo->bind_param("ss", $checkfield, $pk);
not sure if you can mix GET and POST type requests
maybe change this so that pk is passed back as a hidden field ?
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
eg, sort of like this
echo "<form name=\"statusForm\" action=\"test.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"pk\" value=\"".$pk."\">
Here is what your HTML should look like:
<form id="aform" action="thisform.php" method="post">
<input type="checkbox" name="agree" value="yes" />
<input type="hidden" name="secret" value="shhh" />
<input type="submit" value="do it" />
</form>
With the above if you do:
print_r($_POST);
you will get an array that either has [agree] => 'yes' or nothing, depending on if they check the box, so no need to put the array brackets unless you have tons of boxes.
As for the SQL part, I suggest making the column a single integer type, where it can have either a 0 or 1. 0 for unchecked, 1 for checked. For the insert you would do something like:
$check_value = ($_POST['agree'] == 'yes') ? 1 : 0;
$secret_stuff = $_POST['secret'];
mysqli_query("Insert INTO sales_table (secret_column, agree_column)
VALUES ('$secret_stuff', '$check_value')");
That will get your checkbox into the table. To get it out, you should go with:
$results = mysqli_query("SELECT * from sales_table where secret_column = $secret_stuff")
while($row = mysqli_fetch_assoc($results)) {
$checked = ($row['agree_column'] == 1) ? "checked=\"checked\"" : "";
$secret_stuff = $row['secret_column];
}
?>
<form action=blah method=post id=blah>
<input type="checkbox" name="agree" value="yes" <?php echo $checked;?> />
</form>
Sorry, lost steam at the end. But that covers the front end and back end. Use a 1/0 switch, and just set some variable like $checked to the "checked='checked'" if it's a 1.
You're not setting the $pk variable unless isset($_GET["pk"]), yet you're still using it later in the query. This isn't a good idea, since depending on other circumstances, this can lead to bugs. What you want your logic to look like is this:
if pk is not set in form
insert new record
deal with error if insert failed
else
update existing record
check update count and deal with error if 0 records were updated
(perhaps by doing an insert of the missing record)
end
Just as a side note, it looks like the mysql REPLACE function would come in handy for you.
Also, when a checkbox is not checked, the value can be a tricky thing. I have written a function that sets the value to one, if the posted value is set, and zero if not...
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
You can run your posted checkbox value throught that query and always get a one or a zero.