I have a form which has select options for age and radiobuttons for gender. The idea is that the form can be used to search for a specific user by age and gender.
Currently, the form sometimes executes the header (see below) and sometimes not. So Assume, I am logged in as Conor, Conor specifies that he wants to search for a user aged between 20-21 and is male. Upon clicking submit, sometimes the form will find someone, sometimes it will not. I want the query to keep running until a user is found, unless no one exists in the database.
In this case, the header should be executed, taking the user to messages.php because a male aged 20 exists in the database.
Here is my approach:
Form:
<form action="random_chat.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="age_from" id="age_from" value="0"/>
<input type="hidden" name="age_to" id="age_to" value="50"/>
<label for="amount">Age:</label>
from:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value="none"></option>
<?php
for($i = 17; $i <= 50; ++$i) {
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value="none"></option>
<?php
for($i = 18; $i <= 50; ++$i) {
echo "\t", '<option value="', $i, '">', $i, '</option>', "\n";
}
?>
</select>
<!-- I have input type submit above the radio buttons due to table layout -->
<input type="submit" class="btn btn-info" name="submit" value="Click to start chat! " />
<label for="amount">Gender:</label>
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="radio" name="gender" value="any">Any</input>
</form>
PHP code processing the form:
<?php
$refined_gender = htmlentities (strip_tags(#$_POST['gender']));
$age_from = htmlentities (strip_tags(#$_POST['age_from']));
$age_to = htmlentities (strip_tags(#$_POST['age_to']));
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['submit'])){
// if age parameter used...
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender =? AND age BETWEEN ? AND ? ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "sss", $refined_gender, $age_from, $age_to);
mysqli_stmt_execute ($defined_chat);
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
$acc_type = $get_user['account_type'];
if ($acc_type != "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name == $username){
$defined_chat;
} else {
header ("Location: /messages.php?u=$rand_name");
}
} else {
echo "No user found fitting those requirements.";
}
} // while closed
mysqli_stmt_close($defined_chat);
}
?>
I have tried to change the form action to '#', thinking it may be just be refreshing the page, but it didn't work.
Also, how can I make this so that even if one parameter is filled, then still execute search? For example, if I search for a male, with no age defined, it will find a male user. If I search for someone ages between 26-31 and no gender defined, then still execute header?
Edit:
$username is the session variable, which is defined at the very start of random_chat.php.
Do not rely on the value of a submit button to determine if your form was submitted or not. This will not work on all browsers, especially older ones, this value is not always passed back to the server, instead just look at any value inside the form to verify if submission has occurred, or the existence of $_POST in general.
At first sight, what you are attending to do looks to me simpler than the way you are actually trying to achieve it.
Construction you SQL query correctly may be the only thing complicated in here.
Only changing your query could actually already remove your need of the if/else for the account_type and the if/else to check if the current user is the same as the queried one :
$sql = "SELECT
*
FROM
users
WHERE
gender like ? AND
age BETWEEN ? AND ? AND
# with this condition you do not need to test if the user logged is the queried one
username != ? AND
# and with this one, you do not care about exclude adimn either
account_type != 'admin'
ORDER BY RAND()
LIMIT 1";
$defined_chat = mysqli_prepare (
$connect, $sql
);
mysqli_stmt_bind_param(
$defined_chat,
"ssss",
$refined_gender,
$age_from,
$age_to,
$username
);
Then about the fact that you want to be able to search even without any selection on both gender and age, you can use a combinaison of the wildcard % of SQL, the operator like and the ternary operator of PHP (you did maybe already see that I changed gender =? to gender like ? in the query above).
// Means if gender is different than 'any', it will assign the posted value to the variable, otherwise, it will assign the sql wildcard %
$refined_gender = (htmlentities (strip_tags(#$_POST['gender'])) != 'any' ? htmlentities (strip_tags(#$_POST['gender'])) : '%');
// Means if age is different than 'none', it will assign the posted value to the variable, otherwise, it will assign the lowest possible age, 0
$age_from = (htmlentities (strip_tags(#$_POST['age_from'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_from'])) : '0');
// Means if age is different than 'none', it will assign the posted value to the variable, otherwise, it will assign an age bigger than anyone could attain, 9999
$age_to = (htmlentities (strip_tags(#$_POST['age_to'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_to'])) : '9999');
see ternary operators in PHP doc
and see MySQL like and wildcard usage
All in one, your processing PHP script could look like this :
$refined_gender = (htmlentities (strip_tags(#$_POST['gender'])) != 'any' ? htmlentities (strip_tags(#$_POST['gender'])) : '%');
$age_from = (htmlentities (strip_tags(#$_POST['age_from'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_from'])) : '0');
$age_to = (htmlentities (strip_tags(#$_POST['age_to'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_to'])) : '9999');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['submit'])){
$sql = "SELECT
*
FROM
users
WHERE
gender like ? AND
age BETWEEN ? AND ? AND
# with this condition you do not need to test if the user logged is the queried one
username != ? AND
# and with this one, you do not care about exclude adimn either
account_type != 'admin'
ORDER BY RAND()
LIMIT 1";
$defined_chat = mysqli_prepare (
$connect, $sql
);
mysqli_stmt_bind_param(
$defined_chat,
"ssss",
$refined_gender,
$age_from,
$age_to,
$username
);
mysqli_stmt_execute ($defined_chat);
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
header ("Location: /messages.php?u=$rand_name");
} // while closed
echo "No user found fitting those requirements.";
mysqli_stmt_close($defined_chat);
}
You have some mixed logic, so some explanations might help.
1) header('location: ...') will tell the browser to reload the page to the new location. This does not appear to be what you want - you just want to continue execution? NOTE: You should also [nearly] always have "exit();" after a header('location: ... '); line otherwise execution continues which is [nearly] never what you want!)
2) a while loop will continue "while" the condition is true. So the loop continues while there are rows being returned.
3) Running the query again will not return anything new - you can use the same results. So just skip over until you find the result you need!
So, written in English, what you want to do after running the DB query is:
set a tally count to zero
while we have some rows coming from the db {
if that row is not admin {
if that row does not match the current user {
show the result
increase tally count
}
}
}
if tally count is zero {
say "no entries found"
}
So, in code, this is
$foundUsers = 0;
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
$acc_type = $get_user['account_type'];
if ($acc_type !== "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name !== $username) {
$foundUsers = $foundUsers + 1; // Or $foundUsers++ for short
echo 'Matched User: ' . $rand_name . '<br>';
}
}
} // while closed
if ($foundUsers == 0) {
echo "No user found fitting those requirements.";
}
Ok, first of all, if you want to exclude a parameter from the query, you're going to have to build some logic to exclude that variable.
So if $refined_gender = "any", then you need to exclude it from the query. I would change your combobox default values to:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value="-1"></option>
<?php
for($i = 17; $i <= 50; ++$i) {
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value="999"></option>
<?php
for($i = 18; $i <= 50; ++$i) {
echo "\t", '<option value="', $i, '">', $i, '</option>', "\n";
}
?>
</select>
Then, now you've fixed the age between, to filter the gender out. Also, I've added a clause to your WHERE clause: AND account_type != 'admin', this will filter out the admins accounts on the SQL side rather than checking on the PHP side.
// If gender is specified, query gender
if($refined_gender !== "any"){
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender =? AND age BETWEEN ? AND ? AND account_type != 'admin' ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "sii", $refined_gender, $age_from, $age_to);
} else {
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE age BETWEEN ? AND ? AND account_type != 'admin' ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "ii", $age_from, $age_to);
}
mysqli_stmt_execute ($defined_chat);
Suggestion #1: Possible race condition see note in code.
if ($acc_type != "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name == $username){
$defined_chat;<-- don't you need to re-execute this? Seems like you are hitting a race condition since the statement result will never change
} else {
header ("Location: /messages.php?u=$rand_name");
}
} else {
echo "No user found fitting those requirements.";
}
Suggestion #2:
Outside of that you should be sure you aren't getting the current user with a
WHERE name NOT LIKE '%?%' up front in the initial query and get rid of that if statement.
Suggestion #3:
Or better, use the user IDs. What if there's another user with the same name as the searcher, but they're a different person? Base the current user match on UID, not name.
Suggestion #4:
You should absolutely almost never run a select query/statment inside a PHP (or any scripting language) loop. There's always a better way. Filter your data in the database where it's efficient. Even for inserts you can do a single bulk insert much more efficiently than a bunch of insert queries.
Related
for example i have
i have two table in my datbase 1st is list1 and 2nd is list2
<select>
<option name='select' value="0">Select</option>
<option value="list1">List1</option>
<option value="List2">List2</option>
</select>
suppose user in drop down option chose list 1 then data insert in list1 option
if user select list2 then data insert in to list2 how to do this please help me to fix this issue
thanks
mysql_query("INSERT list1 SET title='$titile', subject='$subject'")
and here is complete code
<?php
}
//connect to database
mysql_connect('localhost','root','');
mysql_select_db('pdsd');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$subject = mysql_real_escape_string(htmlspecialchars($_POST['subject']));
// check to make sure both fields are entered
if ($title == '' || $subject == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($title, $subject,$date, $error);
}
else
{
// save the data to the database
$tables = array('list1', 'list2');
if (in_array($_POST['select'], $tables)) {
mysql_query("INSERT {$_POST['select']} SET title='$title',subject='$subject'");
}
or die(mysql_error());
echo "<center>Succesfully add</center>";
echo "<script>setTimeout(\"location.href = 'login.php';\",1500);</script>";
// once saved, redirect back to the view page
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','','','','','','','','','','','','','','','','');
}
?>
As I stated in comments, use a conditional statement and 2 separate queries based on the conditional statement and what the choice equals to the value chosen.
For example and assuming you are using as pure PHP and using a form:
Sidenote: You will need use your own queries here, as seen in commented // query for LIST X.
Another sidenote: The name attribute belongs to <select> and not <option>.
Last sidenote: My omission of action="" is equal to "self". So, you can add action="handler.php" to it if you wish to use separate files.
<form method="post">
<select name="select">
<option value="0">Select</option>
<option value="list1">List1</option>
<option value="list2">List2</option>
</select>
<input type = "submit" name = "submit" value = "Submit">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['select']) && $_POST['select'] == 'list1'){
// query for LIST 1
}
if(isset($_POST['select']) && $_POST['select'] == 'list2'){
// query for LIST 2
}
if(isset($_POST['select']) && $_POST['select'] == '0'){
// Do nothing
}
}
This is but an example and the use of a prepared statement should be taken into account.
https://en.wikipedia.org/wiki/Prepared_statement
Other references you should read related to MySQL:
http://dev.mysql.com/doc/en/insert.html
http://dev.mysql.com/doc/en/update.html
Edit:
You can also use a switch/case statement:
if(isset($_POST['submit'])){
switch($_POST['select']) {
case 'list1':
// query for LIST 1
break;
case 'list2':
// query for LIST 2
break;
case '0':
// Do nothing
break;
}
}
You should first verify that the input is valid, then you can just substitute it into the SQL.
$tables = array('list1', 'list2');
if (in_array($_POST['select'], $tables)) {
mysql_query("INSERT INTO {$_POST['select']} SET title='$titile', subject='$subject'") or die(mysql_error());
}
Make sure you're properly escaping the variables $titile and $subject if they derive from user input, to protect against SQL-inject (use mysql_real_escape_string()). It would be even better if you used MySQLI or PDO so you could use a prepared statement instead of substituting variables into the query.
I have a search form where users can choose a few checkboxes, set a date range, use a wildcard search etc. and via button click it gets sent via ajax to a PHP file and executed in a MySQL query.
In the php file I set up a cascade of if-statements to ensure the query works regardless of the user having chosen certain values, f.e. like this:
// variable from a risk level dropdown menu
if ($_POST['risklevelcount']=="") {
$risklevel = "MASTER.RISK_LEVEL != ''";
}
else {
$risklevel = "MASTER.RISK_LEVEL = "' . $risklevelcount . "'";
}
the variables then are implemented in the where clause of the mysql query, which looks like this:
$result = mysql_query("
SELECT *
FROM MASTER
WHERE
(( ". $buttonvalue ." ) AND ( ". $date . " ) AND ( ". $risklevel ." ))
");
To ensure the query gets executed regardless of the user having checked a checkbox, I analoguously implemented them in a if-clause like this:
if(!empty($checkbox1))
$checkbox1 = "MASTER_CHECK like '%dog%'";
else $checkbox1 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";
if(!empty($checkbox2))
$checkbox2 = "MASTER_CHECK like '%cat%'";
else $checkbox2 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";
if(!empty($checkbox3))
$checkbox3 = "MASTER_CHECK like '%bird%'";
else $checkbox3 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";
If I add these to the above MySQL query where clause I obviously won't get the results I want:
$result = mysql_query("SELECT *
FROM MASTER
WHERE
(
( ". $buttonvalue ." ) AND ( ". $date . " ) AND (". risklevel .") AND
(
(". $checkbox1.") OR (". $checkbox2.") OR (". $checkbox3.")
)
)
");
I won't get for example results for 'dog' AND 'cat' but not 'bird' (= checkbox 1 and 2 checked but not 3).
I know this is a really stupid approach from the start, regardless of the checkboxes. I sadly don't know how to do any better yet. If someone could point me in the right direction, I would be very glad. I think there is a much more smart way to do it, f.e. with arrays? I just really lack a real basis knowledge!
I suppose you have a form like this one :
<form id="myFormId" method="POST" action="index.php">
<div>
<label for="level">Level :</label>
<select name="risklevelcount">
<option value="">-- all level --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div>
<label>Any Pet ?</label>
<input type="checkbox" name="pet[]" value="dog">dog
<input type="checkbox" name="pet[]" value="cat">cat
<input type="checkbox" name="pet[]" value="bird">bird
</div>
<input type="submit" value="submit">
</form>
Here is what I recommend for PHP part :
$strWhere = '1=1';
if(true === isset($_POST['risklevelcount']) && true === is_numeric($_POST['risklevelcount']))
{
$strWhere = ' AND MATER.RISK_LEVEL = '.mysql_escape_string($_POST['risklevelcount']);
}
if(true === isset($_POST['pet']) && 0 < sizeof($_POST['pet']))
{
$strWhere .= 'AND (';
foreach($_POST['pet'] as $pet)
{
$strWhere .= ' MASTER_CHECK like "%'.mysql_escape_string($pet).'%" OR ';
}
//remove last OR
$strWhere = substring($strWhere, 0, -3);
$strWhere .= ')';
}
$result = mysql_query("SELECT * FROM MASTER WHERE ".$strWhere);
I agree with mate, use mysqli or PDO is better, at least escape strings.
Moreover, stop saying in your queries MASTER.RISK_LEVEL != '' or worst MASTER.CHECK = '' OR MASTER.CHECK != ''.
In the first case, I supposed risk_level is always defined. So no need to say risk_level != ''. And in the second case, Its useless to say I want string null or not null. Just dont ask and you 'll have all results.
EDIT :
If you check the form at the beginning of my answer, I've add an ID which is myFormId.
So with jQuery, if you want to serialize your form data, just do :
javascript:
var formData = $('#myFormId').serialize();
I have mySQL table containing rows of user reviews of films. All columns a are functional except for the 'liked' column. The 'liked' column is a boolean value.
This
The table must be displayed on my website, converting the boolean to a 'yes' or 'no'. Here is the code for the table:
while($review = $reviews->fetch_object("Review")) {
$liked = $review->liked;
$convert = ($liked) ? 'yes' : 'no' ;
echo "<tr> <td>{$review->reviewer} </td> ";
echo "<td>{$review->comment} </td>";
echo "<td> $convert </td></tr>";
As you can see the conversion is functional.
The page also contains a form where users can submit their reviews. Using a checkbox, users 'check' if they like the film, or don't check if they don't.
<div class="form-group">
<label for="liked" class="col-xs-2 c">Did you like this film?:</label>
<div class="col-xs-10">
<input name="liked" type="checkbox" value="1" > Tick yes if you did
</div>
</div>
In a seperate PHP file; 'Process-review', I use an INSERT query to insert new rows into the table.
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['film_id']))
{
$reviewer = $_POST['name'];
$comment = $_POST['comment'];
$film_id = $_POST['film_id'];
if(isset($_POST['liked']))
{
$liked = $_POST['1'];
}
else
{
$liked = $_POST['0'];
}
$db->query("INSERT INTO review (film_id, reviewer, liked, comment) VALUES('$film_id', '$reviewer', '$liked', '$comment')");
header('Location: show-film.php?id='.$film_id);
}
else{
$name = null;
echo "no name supplied";
}
All other fields work except for the 'liked' field. As you can see I have tried using an if statement within the initial if statement to return a '1' if the checkbox is ticked and '0' if the checkbox isn't ticked. Yet when I check the box, the table still returns a 'no'. Even if i change the $convert so both values are 'yes' it still returns no which begs the question where is it getting the 'no' from.
Here is an image of the table to give you a visual representation of what I'm working with here
You're trying to insert values that don't exist.
Replace your if condition with:
if(isset($_POST['liked']) && $_POST['liked'] == 1)
{
$liked = 1;
}
else
{
$liked = 0;
}
Aside from that, you're opening yourself up to an injection attack.
You should use prepared statements.
At the very least run every variable you're passing to the database through mysqli_real_escape_string.
I am totally stuck here and found tens of samples on posting to get and set values. What I am trying to do is -
Let a user enter a vehicles year model into a textbox in my form (set to post)
I then need to get this value to a variable state
$vehicle_year = $_GET['vyear'];
First error is here... vyear is the name and id for my textbox. Error - Undefined index 'vyear'. There is no submission of the form etc, because I am still on the same form/page.
With this value captured, I then search my database to return all of the manufacturers that has a year (as returned) attached to it -
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
Obviously it does not work because I still do not have the value as yet returned from above with the undefined error. I've tried to change the name and id of the textbox, no luck.
Once these records has been returned, I need to add the values to a select (drop down) box. I have no idea how to get the values in there - seems I need to run a loop, which I know how to, just don't know how to add the options to the select box.
Please note that my form is NOT submitted, I need to load all the relevant data first before it gets submitted.
Any help will be appreciated, thanx guys.
P.S. I will add against sql injection once I know how to get the values and add the options. Just need the basics to get me going.
HTML:
//This would be my code...
Search Just my Wheels
Year
<?php
$vehicle_year = isset($_POST['vehicleyear']) ? $_POST['vehicleyear'] : -1;
if ($vehicle_year == -1) {
echo 'No Value Returned...';
//returns no value...
} else {
//How to get the value and echo it out...
echo $vehicle_year;
}
//$query = "SELECT * FROM (SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year' ORDER BY `cid` DESC LIMIT 1, 10) AS `table` ORDER BY `cid` ASC";
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$vehicle_id = $line['cid'];
$vehicle_year = $line['year'];
$manufacturer = $line['carfindmake'];
//Get manufacturer data...
$images = get_make($vehicle_year);
if (!empty($make)) {
echo 'No data';
} else {
echo 'Found stuff';
}
}
?>
<td align="right"><span style="visibility:hidden" id="makelabel"><strong>Make</strong> </span></td>
<!--<td><input name="make" id="make" type="text" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>-->
<td><select name="make" id="make" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>
2) This is causing an error when your form has not yet been submitted because the value is not set.
Fix this by the following:
$vehicle_year = '';
if ( isset( $_POST['vyear'] ) ) {
$vehicle_year = $_POST['vyear'];
}
1 - If the form is set to POST, you've got to use $_POST["vyear"] to recover the value.
2 - Double check the case of the textbox's name.
my form (set to post)
$vehicle_year = $_GET['vyear'];
If your form is set to use POST, you'll need to access the form elements through the $_POST superglobal as such:
$vehicle_year = $_POST['vyear'];
If you're having issues because an index may or may not be set, use PHP's isset() to check. If the index isn't set, it won't cause an error.
if(isset($_POST['vyear'])) {
$vehicle_year = $_POST['vyear'];
}
I am getting an "Undefined index" error when submitting a form with an un-checked checkbox. Is there any other way besides running an "isset" or "empty" check on each individual posted value?
I have looked at this Question and am having trouble believing that this is the only solution.
Below is some example code:
EDIT: please not that these are not the actual names of the tables columns; they are named uniquely (like "postAddress, displayPhone, student, etc.)
You could write a function that checks whether a checkbox was checked:
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
Now call that function in your query like this:
$sql = 'UPDATE table SET '.
'checkbox1 = '. checkbox_value('checkbox1') .','.
'checkbox2 = '. checkbox_value('checkbox2') .','.
'checkbox3 = '. checkbox_value('checkbox3') .','.
'checkbox4 = '. checkbox_value('checkbox4') .','.
'checkbox5 = '. checkbox_value('checkbox5') .','. "LIMIT 1";
If you want a on/off checkbox you can write a hidden value before you write the checkbox.
<input type="hidden" name="checkbox1" value="no" />
<input type="checkbox" name="checkbox1" value="yes" />
This will always return a value, either no (default unless checkbox is checked by default) or yes.
You can validate input with the filter functions with FILTER_VALIDATE_BOOLEAN.
Its easier if you write a function for this, like formCheckbox($name), with options for values (value 'on' means checkbox is checked by default), attributes, etc.
try the following
<?php
//first part of the query
$query = "UPDATE table SET ";
$howManyCheckboxes = 5;
//for every checkbox , see if it exist , if it is, add it to the query
for($i=1;$i<=$howManyCheckboxes;$i++)
{
if(isset($_POST['checkbox'.$i]))
{
$query = $query . " checkbox".$i."='".escape($_POST['checkbox'.$i])."',";
}
}
//lets remove the last coma
$query = substr($query,0,-1);
//add the rest of the query
$query = $query . " LIMIT 1";
$result = mysql_query( $query );
if( ! $result ) echo "um, not everything went as expected.";
?>