How to insert multiple checkbox value respect their id - php

I fetch some value from database. and want to update the database table respect their ids.
here is my code:
<?php
$sql = "SELECT * FROM tbl_ads ORDER BY ads_id DESC LIMIT $START, $LIMIT";
$result = mysql_query( $sql );
$num = mysql_num_rows( $result );
if( $num > 0 ){
while( $row = mysql_fetch_array( $result ) ){ ?>
<tr bgcolor="#E1E1E1">
<td align="left" valign="top" bgcolor="#F1F1F1" class="BlackText2">
<?php echo $row['title'];?>
</td>
<td align="left" valign="top" bgcolor="#F1F1F1" class="BlackText2">
<?php echo substr($row['description'], 0, 40);?>
</td>
<td align="left" valign="top" bgcolor="#F1F1F1">
<?php echo $row['mywebsite'];?>
</td>
<td align="center" valign="top" bgcolor="#F1F1F1">
<input type="hidden" name="ads_id[]" value="<?php echo $row['ads_id'];?>">
<input type="checkbox" name="feature[]" value="feature">
</td>
<?php
if( isset( $_REQUEST['submit'] ) ){
$feature = $_POST['feature'];
$ads_id = $_REQUEST['ads_id'];
if( empty( $feature ) ){
echo( "You didn't select any buildings." );
}else{
$N = count( $feature );
$M = count( $ads_id );
echo("You selected $N door(s): ");
for( $i=0 ; $i < $N ; $i++ ){
for( $j=0 ; $j < $M ; $j++ ){
echo ( $feature[$i] . " " );
echo $update_feature = "UPDATE tbl_ads SET `featureads` = '".$feature[$i]."' WHERE ads_id ='".$ads_id[$j]."'";
$result_feaure = mysql_query($update_feature);
}
}
}
}
?>
but my problem is when I update the featureads column respect ads_id column then all column are selected.
how to solve this problem?

It looks like you have a table that stores all of the ID's of something and you want someone to be able to define each record to be a featured "ad" and do it all at once.
My suggestion would be to change the code:
<input type="checkbox" name="feature[]" value="feature">
To reflect the selected feature and backtrack your functionality to suit.
For example:
<input type="checkbox" name="feature[]" value="<?php echo $row['ads_id']; ?>">
A check box value is set when the checkbox is checked, your code above will mean that the value of the feature checkbox will always be "feature" but it wont relate the the 'ads_id' field.
By changing to the example above you could then:
update the table to say that none of the adds are featured
loop through the feature[] form variable to update the table to set the featured column to true for the selected columns.
I have done a similar thing but used radiogroups because check's only give you a value if they are checked.
E.g:
<label><input type="radio" name="feature[$id]" value="yes"/>yes</label>
<label><input type="radio" name="feature[$id]" value="no"/>no</label>
hth :)

Related

Database won't stay updated after switching script

I'm trying to update this database, and I've verified within this script that the update is completed, and that the $nw and $p variables are correct.
<?php
session_start();
$num = (int) $_SESSION["cart"];
$cart = $num + 1;
$_SESSION["cart"] = (string) $cart;
$nme = $_POST['nameofitem'];
$pst = $_SESSION["user"];
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$query = "select * from Items where Items.Id = '$nme'";
$result = $db->query($query) or die ($db->error);
$item = $result->fetch_array();
$nw = $item[5] - 1;
$p = (int) $pst;
echo $p;
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
$db->query($query3) or die ("Invalid insert " . $db->error);
$query2 = "insert into Bought (Name, Cost, BuyerID) values ('$item[1]', '$item[4]', '$pst')";
$db->query($query2) or die ("Invalid insert " . $db->error);
header("Location: store.php");
?>
However, when it redirects to this script, it echoes the information as if it weren't updated. What is the problem?
<?php
session_start();
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
$user = $_SESSION["user"];
$pw = $_SESSION["pw"];
# determines number of items in cart to display
if (!isset($_SESSION["category"]))
$_SESSION["category"] = "Book";
if (isset($_POST["Ccategory"])) {
$cat = $_POST["Ccategory"];
$_SESSION["category"] = $cat;
}
if (!isset($_SESSION["cart"]))
$_SESSION["cart"] = "0";
$cart = $_SESSION["cart"];
?>
<!DOCTYPE html>
<html>
<?php # setting up table with items to buy ?>
<table border = "1" border-spacing = "5px" >
<caption><h2> UVA Bookstore 2.0</h2>
<p align=right> Items in cart: <?php echo $cart?> </p> <br />
<b><i>Welcome to the new and improved bookstore with a better selection than ever</i></b>
<br/><br/>
</caption>
<tr align = "center">
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Number left</th>
<th>Buy</th>
</tr>
<?php
$category = $_SESSION["category"];
$query = "select * from Items where Items.Category = '$category'";
$result = $db->query($query) or die ($db->error);
$rows = $result->num_rows;
for ($i = 0; $i < $rows; $i++)
{
$row = $result->fetch_array();
?>
<form action="addtocart.php"
method="POST">
<tr align = "center">
<td>
<?php
echo $row[1];
?>
</td>
<td> <?php echo $row[3];?> </td>
<td> <?php echo $row[4];?> </td>
<td> <?php echo $row[5];?> </td>
<?php # sets up add to cart button that adds item to cart ?>
<td> <input type = "hidden" name ='nameofitem'
value= "<?php echo $row[0]?>">
<input type='submit' value='Add to Cart'> </input> </td>
</tr>
</form>
<?php
}
# form to check out and go to summary page ?>
<form action = "store.php"
method = "POST">
<tr align = "center"> <td>
<select name = "Ccategory">
<option value = "Book">Books</option>
<option value = "Music">Music</option>
<option value = "Car">Cars</option>
</select>
<input type = "hidden" name = "cat"> </td>
<td> <input type = "submit" value = "Switch Category"> </td>
</form>
<form action="summary.php"
method="POST">
<td> <input type = "submit" value = "Check out"> </td> </tr>
</table><br/>
</form>
</html>
Have you tried changing
$query3 = "update Items set Quantity = '$nw' where Id = '$p'";
to
$query3 = "update Items set Quantity = '$nw' where Id = $p";
The best way to determine if an UPDATE should work is to replace it with a SELECT containing the same WHERE clause. This way you can see what rows would be changed if you were to run the original query.
Otherwise, it seems to be the case that your changes in the current transaction are never committed. Is this the only script that has an issue with updates to the database? Please see the PHP manual for more information:
//mysqli::commit -- mysqli_commit — Commits the current transaction
bool mysqli::commit ([ int $flags [, string $name ]] )
A commit should be issued when you are done doing all updates that have dependencies (or for those that are atomic), however, you don't always have to commit depending on the configuration of your server. Also, it looks like your script has SQL injection vulnerabilities as other have mentioned. It would probably be best to use prepared statements or sanitize your inputs.

Update form submit depending on selected row

I am a novice but I am trying to pull this thing together.
I am trying to build a billing system. Within the DB, each invoice has a PK with items such as invoice date, due date, etc. I have another table that lists the items (itemID is the PK) with a relationship between a Invoice ID in both tables. My issue is with the Items table.
In cases where only one item is on the invoice, I can update records. However, my problem is when I have more than one entry, I can only edit the last entry in the row.
Here is a illustration of what my table looks like. The Green arrow indicates the last row in the items list (which I can update); the red arrow indicates the row I cannot update.
As you can see, I am able to get the individual itemID into a variable to display alongside the form submit button:
<td>
<input type="submit" name="submit_items" value="Submit" />'
.$row->item_id.'
</td>
I am wondering how would I "link" / "associate" the individual item id so it will run the corresponding MySQL. For example, I'm looking for the MySQL query to update itemID row 4164 when I click the submit button for itemID 4164. Currently, my code is only updating the last itemID.
Here is the MySQL query which is able to update the final item:
UPDATE o70vm_invoices_items SET
invoice_id = $invoiceID,
name = '$program',
`desc` ='$forWeek',
value = $value,
amount = $qty
WHERE id=$id
I have tried to change the WHERE statement to this:
WHERE id=".$row->item_id.""
However, no item is displayed. I think I am pretty close. Been working at it for a the few days. If there is a way to alter the code to automatically get the row ID of where the form submit button is located, I will be a major step closer to completing this project. A step I can't seem to do by myself. Thanks if anyone is listening. :)
Any suggestions on how to handle this operation, so much appreciated.
Here is my complete code, in case there are many questions I have not answered with enough detail:
$queryItems = "select
o.`id` as 'item_id',
o.`invoice_id` as 'invoice_id_on_items',
o.`name` as 'program',
o.`value` as 'fee',
o.`amount` as 'qty',
o.`desc` as 'forweek',
group_concat( o.`desc` separator ' & ' ) as 'forweekgroup',
round( sum( ( o.`value` ) * ( o.`amount` ) ),2 ) as 'inv-total'
from `o70vm_invoices_items` o
where o.`invoice_id` = $invoiceSelected
GROUP BY o.id";
// storing the result of this MySQL query
$resultItems = mysql_query( $queryItems );
echo'
<form action="" method="post">
<div>';
echo "<h2>Invoice Items</h2>";
if( $resultItems ){
echo '
<table>
<tr>
<th scope="col">Invoice ID</th>
<th scope="col">Item ID</th>
<th scope="col">For Services Rendered</th>
<th scope="col">Program</th>
<th scope="col">Fee</th>
<th scope="col">Quantity</th>
<th scope="col">Total Fees</th>
<th scope="col">Edit</th>
</tr>';
$id=0; /* Each field / element that has an id must have a unique id ~ use a counter to achieve this */
$Invoice_Amount=0.00;
while( $row = mysql_fetch_object( $resultItems ) ){
$id++;/* Increment the id counter */
echo '
<tr>
<td>'.$row->invoice_id_on_items.'</td>
<input type="hidden" title="'.$row->invoice_id_on_items.'" name="invoice_id" size="10" id="invoice_id" value="' . $row->invoice_id_on_items. '" />
<td>'.$row->item_id.'</td>
<input type="hidden" title="'.$row->item_id.'" name="id" size="13" id="id" value="'.$row->item_id. '" />
<td>
<input type="text" title="'.$row->forweek.'" name="desc" size="15" id="desc" value="' . $row->forweek. '" />
</td>
<td>
<input type="text" title="'.$row->program.'" name="name" size="50" id="name" value="' . $row->program. '" />
</td>
<td>
<input type="number" title="'.$row->fee.'" name="value" size="3" id="value" value="' . $row->fee. '" />
</td>
<td>
<input type="number" title="'.$row->qty.'" name="amount" size="3" id="amount" value="' . $row->qty. '" />
</td>
';
$Fee = floatval($row->fee);
$Qty = floatval($row->qty);
$ItemFee=$Fee*$Qty;
echo '
<td>
<input type="text" title="'.$ItemFee.'" name="total_fee" size="3" id="total_fee" value="' . $ItemFee. '" />
</td>
<td>
<input type="submit" name="submit_items" value="Submit" />'
.$row->item_id.'
</td>
</tr>';
$Invoice_Amount+=$ItemFee;
}
echo '
<tr>
<td colspan=6></td>
<td>$'.$Invoice_Amount.'</td>
</tr></table>
</div>
</form>';
} else {/* Do not give away too much information and degrade gracefully */
echo "We can't seem to pull the data information on this one, baby. Sorry. Code must be wrong.";
echo "Error:".mysql_error();
}
/*
EDIT RECORD START
*/
// get variables from the URL/form
$id = $_POST['id'];
$invoiceID = htmlentities($_POST['invoice_id'], ENT_QUOTES);
$program = htmlentities($_POST['name'], ENT_QUOTES);
$forWeek = htmlentities($_POST['desc'], ENT_QUOTES);
$value = htmlentities($_POST['value'], ENT_QUOTES);
$qty = htmlentities($_POST['amount'], ENT_QUOTES);
//NOTE: desc is a MySQL reserved word so we need to `desc`
$stmt = "UPDATE o70vm_invoices_items SET
invoice_id = $invoiceID,
name = '$program',
`desc` ='$forWeek',
value = $value,
amount = $qty
WHERE id=$id";
Pseudo code to guide you in updating the row you want rather than all rows in one hit. No doubt there are lots of other methods too...
while( $row = mysql_fetch_object( $resultItems ) ){
/*
Copied quickly so if there are cells missing you should get the idea
*/
echo '
<tr data-id="'.$row->item_id.'">
<td>'.$row->invoice_id_on_items.'</td>
<td>'.$row->item_id.'</td>
<td><input type="text" title="'.$row->forweek.'" name="desc_'.$row->item_id.'" size="15" id="desc" value="' . $row->forweek. '" /></td>
<td><input type="text" title="'.$row->program.'" name="name_'.$row->item_id.'" size="50" id="name" value="' . $row->program. '" /></td>
<td><input type="number" title="'.$row->fee.'" name="value_'.$row->item_id.'" size="3" id="value_'.$row->item_id.'" value="' . $row->fee. '" /></td>
<td><input type="number" title="'.$row->qty.'" name="amount_'.$row->item_id.'" size="3" id="amount_'.$row->item_id.'" value="' . $row->qty. '" /></td>
<td>
<input type=\'button\' value=\'Submit\' />
/* Notice it is now a simple button */
<input type="hidden" title="'.$row->item_id.'" name="id_'.$row->item_id.'" size="13" id="id_'.$row->item_id.'" value="'.$row->item_id. '" />
<input type="hidden" title="'.$row->invoice_id_on_items.'" name="invoice_id_'.$row->item_id.'" size="10" id="invoice_id_'.$row->item_id.'" value="' . $row->invoice_id_on_items. '" />
</td>
</tr>';
}
In the head section, something like the following:
( this is untested but the idea is that it will send the data via ajax request to the receiving script that does the processing of the data ~ ie: the form action )
<script>
function initialise(){/* establish listeners for button click events */
var col=document.querySelectorAll('input[type="button"]');
if( col )for( var n in col ){
if( col[n] && typeof(col[n]))=='object' && col[n].nodeType==1 ) col[n].addEventListener('click',processclicks,false );
}
}
function cbprocclick(r){
alert( r );
}
function processclicks(event){/* Process the button click */
var el=typeof(event.target)!='undefined' ? event.target : event.srcElement;
var parent=el.parentNode.parentNode;
var id=parent.dataset.id;
var callback=cbprocclick;
var col=parent.querySelectorAll('input');
var fd=new FormData();
for( var n in col ) fd.append( n, col[n] );
/* Forgot the custom field for the ID */
fd.append( 'record_id', id );
var request = new XMLHttpRequest();
/* here you can setup a callback to handle messages sent back */
if( request.status==200 && request.readystate==4 ){
callback.call( this, request.responseText ); /* etc */
}
request.open( "POST", "http://example.com/scriptname.php" );
request.send( fd );
}
document.addEventListener( 'DOMContentLoaded', initialise, false );
</script>
When data is submitted each of the fields will have the record ID appended to the end - example: desc_4 etc
The javascript function processclicks has a custom field ( sorry, forgot to include that yesterday evening ) called record_id which is the $row->item_id - so at the receiving end you should be able to retrieve the records using this record_id
If you are posting to the same page, I'd suggest that the code that handles the actual data entry to the db is at the top of the page and then a structure like the following:
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['record_id'] ) ){
/* Make sure we discard any output ther emay have been to this point */
#ob_clean();
/* For debugging, try: */
print_r($_POST);
/* Use the console to see what your request looks like and also the response */
/* The record id sent as custom field */
$recordid=$_POST['record_id'];
/* The records sent in the request */
$description = htmlentities( $_POST['desc_'.$recordid], ENT_QUOTES );
$invoiceid = htmlentities( $_POST[ 'invoice_id_'.$record_id ], ENT_QUOTES );
$program = htmlentities( $_POST[ 'name_'.$record_id ], ENT_QUOTES );
$fee = htmlentities( $_POST[ 'value_'.$record_id ], ENT_QUOTES );
$qty = htmlentities( $_POST[ 'amount_'.$record_id ], ENT_QUOTES );
/* Then construct your sql */
$sql="update `o70vm_invoices_items` set
`invoice_id` = '$invoiceid',
`name` = '$program',
`desc` = '$description',
`value` = '$fee',
`amount` = '$qty'
where `id`='$recordid';";
/*
Because you are posting data via ajax
you only want to submit data, not load the
entire page again
*/
exit();
}
}

Pass PHP array through Select Option Fields

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

Need help for database update query in php form - Joomla database

Let's say I have a table with 10 records and I want to take name, lastname and rank from those 10 records. First I do something like this:
<?php // DATABASE SELECT QUERY
$db =& JFactory::getDBO();
$query="SELECT name, lastname, rank
FROM table
ORDER BY rank ASC";
$db->setQuery($query);
$rows = $db->loadObjectList(); ?>
Then, I add some fields in to my form that contain table's values, so I can edit them through form:
<form action="#" method="post" name="form">
<table><?php $count = 0; while ($count < 10){
$name = $rows[$count]->name;
$lastname = $rows[$count]->lastname;
$rank = $rows[$count]->rank; ?>
<tr>
<td><input name="name" value="<?php echo $name ?>" type="text" /></td>
<td><input name="lastname" value="<?php echo $lastname ?>" type="text" /></td>
<td><select name="rank">
<option value="<?php echo $rank ?>"><?php echo $rank ?></option>
<option disabled="disabled" value="...">...</option>
<?php for ($i = 0; $i <= 100; $i++){ ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?>
</select></td>
</tr><?php $count++;}?>
</table>
<input class="something" name="updatemod" type="submit" value="UPDATE" />
</form>
Next, before Select query, I have add an update query using this method below, so when I press the update button, update my DB:
// DATABASE UPDATE QUERY
if (isset($_POST['updatemod']) or isset($_GET['updatemod'])){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = '".$_POST["name"]."',
SET lastname = '".$_POST["lastname"]."',
SET rank = '".$_POST["rank"]."'
";
$db->setQuery($query);
$db->query();}
But... Nothing is working!!! I have done exactly the same thing for an other form and it's working perfect! The only difference between those two forms, is that I am not using this while loop at the other form. So, maybe it has to do with this or something??? I don't know, at this point is where my knowledge confused, so I need your help!
I think you are trying to update all the rows in your table.
If that is the case,You need to do something like this.
<?php // DATABASE SELECT QUERY // also you should select your unique id field
$db =& JFactory::getDBO();
$query="SELECT name, lastname, rank,id
FROM table
ORDER BY rank ASC";
$db->setQuery($query);
$rows = $db->loadObjectList(); ?>
In your form you are placing element name as single but your requirement is to edit all the rows at one click you should use input names as array.Also here you have to introduce a new id field too for update condition
<form action="#" method="post" name="form">
<table><?php $count = 0; while ($count < 10){
$name = $rows[$count]->name;
$lastname = $rows[$count]->lastname;
$rank = $rows[$count]->rank;
$id = $rows[$count]->id; ?>
<tr>
<td><input name="uid[]" value="<?php echo $id?>" type="hidden" />
<input name="name[]" value="<?php echo $name ?>" type="text" /></td>
<td><input name="lastname[]" value="<?php echo $lastname ?>" type="text" /></td>
<td><select name="rank[]">
<option value="<?php echo $rank ?>"><?php echo $rank ?></option>
<option disabled="disabled" value="...">...</option>
<?php for ($i = 0; $i <= 100; $i++){ ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option> <?php } ?>
</select></td>
</tr><?php $count++;}?>
</table>
<input class="something" name="updatemod" type="submit" value="UPDATE" />
</form>
Also in your Update Query also required loop and where cluase
// DATABASE UPDATE QUERY
if (isset($_POST['updatemod']) or isset($_GET['updatemod'])){
$db =& JFactory::getDBO();
$total_rows = sizeof($_POST["uid"]);
for($i =0; $i<$total_rows;$i++){
$query = "UPDATE table
SET name = '".$_POST["name"][$i]."',
lastname = '".$_POST["lastname"][$i]."',
rank = '".$_POST["rank"][$i]."'
WHERE id = '".$_POST["uid"][$i]."'
";
$db->setQuery($query);
$db->query();
}
}
I think this will solve your problem.
Here i just mentioned the "id" as your unique key of the table that may differ.But you will get the idea , i hopes
But this is a worst case update condition Bcoz you just imagine the table with 1000 rows.
It will take too long to get the result.
Try to update single row with proper method.It is the best method.
Hope this may help you.

Input Values and Select Return Data

I'm trying to create a webpage where the user can submit information that they know and select information they'd like returned. For example, if they know the ID number for their submission, they can enter it and ask for the returned values to be the ID number and product name.
The information that's being retrieved is stored in a MySQL database, and the html page is laid out with a select menu, text boxes, and checkboxes (so that the user can select a name or enter other information, and then use the checkboxes to select the other information they want returned).
Here's the relevant html:
<table><tr>
<form name="input" method="post" action="next.php">
<td width="120">Flowcell ID:<br />
<select name = "Flowcell_ID">
<option disabled="disabled" selected="selected">
Select...
</option>
<?php
$link = mysqli_connect("localhost","user","pass","db");
$query = "SELECT DISTINCT ID FROM table";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$id = $row['ID'];
echo "<option value=\"$id\">$id</option>";
}
mysqli_close($link);
?>
</select></td>
</tr><tr>
<td width="120">Name:<input type="text" name="Name" /></td>
</tr><tr>
<td width="120">Date:<input type="text" name="Date" /></td>
</tr><tr>
<td width="120">Group:<input type="text" name="Group" /></td>
</tr><tr>
<td width="120"><input type="checkbox" name="options[]" value="ID">ID</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Name">Name</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Date">Date</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Group">Group</input></td>
</tr></table>
The only php I have so far is:
$id = $_POST['ID'];
$name = $_POST['Name'];
$date = $_POST['Date'];
$group = $_POST['Group'];
How would I produce a MySQL query that looks like
SELECT [checked checkboxes] FROM table WHERE [information field] = [user-entered information]
?
Thanks!
You can build the query incrementally:
$fields = array(
'ID' => 'id',
'Name' => 'name',
'Date' => 'date',
'Group' => 'group',
);
$query = 'SELECT'; // Optional fields to be displayed may go here
$comma = ' '; // and if they do, start with $comma = ', ';
$where = array();
foreach($fields as $post => $mysql)
{
// here we have $post equal to 'ID', our POST field, and
// $mysql equal to, say, 'Id' -- the MySQL field name.
// Check whether options['ID'] is set. If so, we must get
// the _POST[ID] field and check its contents against "Id" field in DB.
if (in_array($post, $_POST['options']))
{
$query .= "$comma$mysql";
$comma = ', ';
// Add WHERE condition
$where[] = "$mysql = '" . mysql_real_escape_string($_POST[$post]) . "'";
}
}
// $comma, the separator between option fields, also doubles up as a check
// to see whether we have conditions.
// another possibility would be, "if (empty($where))"
if (' ' == $comma)
die("You must select at least one checkbox!");
$query .= ' FROM table WHERE ';
// Build WHERE condition
$query .= '(' . implode(' AND ', $where).')';
// Other conditions may go here (e.g. " AND record_valid = 1 ")
$query .= ';';

Categories