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();
}
}
Related
I'm building a wordpress plugin for fun, and I want something crazy, I think.
make a form with a foreach loop with an entire database table.
change the data of the whole database table
update the database data of this table
I've got this until now, but I'm stuck when I want to update the records.
<form method="post">
<input type="hidden" name="form_hidden" value="Y">
<table>
<tbody>
<?php
global $wpdb;
$post_id = $wpdb->get_results("SELECT * FROM tbl_name ORDER BY id ASC");
foreach($post_id as $row){
echo '<tr><td>' . $row->id . '</td><td><input type="text" name="' . $row->name . '" value="' . $row->name . '" /></td></tr>';
}
?>
</tbody>
</table>
<input type="submit" name="Submit" value="Update Options" />
</form>
<?php
if($_POST['form_hidden'] == 'Y') {
//update database
global $wpdb;
foreach($_POST['name'] as $item){
$wpdb->replace( 'tbl_name', ); // <- some kind of array here
}
}
There are multiple issues, I guess.
wpdb::replace(...) replaces the columns of all rows with ONE value;
that is not what you want, correct?
To update the correct row in your table, you should refer to the corresponding primary key. I guess "id" in your case.
To store multiple values in your form as an "array", you have to use field names like "name[]".
Lets put it all together:
// in your form creation loop...
foreach($post_id as $row){
echo '<tr><td><input type="text" name="id[]" value="' . $row->id . '" /></td><td><input type="text" name="name[]" value="' . $row->name . '" /></td></tr>';
}
// processing the new values
foreach($_POST['id'] as $I => $id) {
$sql = $wpdb->prepare("UPDATE tbl_name SET name=%s where id=%d"
, $_POST['name'][$I]
, $id
);
$wpdb->query($sql);
}
These are only the interesting parts - just combine it with your existing code. See
Useful links:
https://developer.wordpress.org/reference/classes/wpdb/prepare/
https://developer.wordpress.org/reference/classes/wpdb/query/
https://www.php.net/manual/en/faq.html.php
Good luck!
I have created a while loop
while($row = mysql_fetch_Array($result)) {
echo '<tr class="record"> <td></td><td>'
. $row['company'] .'</td><td>'
. $row['project'].'</td><td>'
. $row['assignee']. '</td><td>'
. $row['current_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['start_date'])).'</td><td>' ..'</td><td>'
. $row['next_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['next_date']))
.'</td></tr>' ;
}
This displays correctly but my question is:
How can the user select an individual row so he/she can edit it. I was hoping that the user can select which row they wanted and they would be taken to another screen where they can make the changes. I can figure out how to do the part where I can update the data. But it is the selecting the row and collecting correct data I dont understand how to do.
Embed an <a href='update.php?id=> somewhere in there which carries the record id to the update script as a parameter in the query string:
while($row = mysql_fetch_Array($result)) {
echo '<tr class="record"> <td></td><td>'
// Insert a link with an id parameter.
// Use whatever column value uniquely identifies your row
. ' Edit this! '
// etc...
// etc...
// etc...
.'</td></tr>' ;
}
And retrieve it on the update script via:
// Assuming an integer id was passed...
// if it is some other string value, escape and quote it accordingly.
$id = intval($_GET['id']);
And you will want to check that the user making the edit has permission to edit that record. In other words, verify that the record is owned by the user is logged in, since anyone could technically visit the URL with any id, whether or not it belongs to them. As in:
UPDATE yourtable SET col1 = 'whatever', col2 = 'whatever' WHERE id = $id AND user_id = 'logged_in_user'
Create some sort of primary key (a new field that will be different for each row/entry) in your database. Example: an ID field
Create a separate page for updating that accepts a GET parameter id. Ex: update.php
Validate and sanitize the id parameter (ensure it is a valid id, not an SQL injection attempt, and the user has the privileges to edit this id)
Load info from database for that id. Ex: SELECT fields FROM table WHERE id = $id
Display a form so user can edit the information.
Validate form input and update the table. Ex: UPDATE table SET field1=newVal WHERE id = $ID
First of all, you need to create a primary key in the table, suppose primary_key in this case, so as to access the particular row having a definite and unique ID.
Secondly, add one more column to your table:
while($row = mysql_fetch_Array($result)){
echo '<tr class="record"> <td></td><td>'
. $row['company'] .'</td><td>'
. $row['project'].'</td><td>'
. $row['assignee']. '</td><td>'
. $row['current_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['start_date'])).'</td><td>' ..'</td><td>'
. $row['next_milestone'] . '</td><td>'
. $date=date("d-m-Y", strtotime($row['next_date']))
.'</td>' ;
?>
<td>
<form action='update.php' method='post'>
<input type="hidden" name="id" value="<?php echo $row['primary_key']; ?>">
<input type="submit" value="Edit">
</form>
</td>
<?php
echo "</tr>";
}
?>
And now you know which row's details you need to display in the form at update.php
The code on update.php goes like:
<?php
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM table WHERE primary_key = '$id'");
$info = mysql_fetch_array($result);
?>
<form action='target.php' method='post'>
Company: <input type="text" name="company" value="<?php echo $info['company']; ?>">
Project: <input type="text" name="project" value="<?php echo $info['project']; ?>">
.
.
<input type="hidden" name="id" value="<?php echo $info['primary_key']; ?>">
<input type="submit" value="Save Changes">
</form>
And then on target.php all you have to do is use the command:
mysql_query("UPDATE table SET company='".$_POST['company']."' AND project='".$_POST['project']."' WHERE primary_key='".$_POST['id']."');
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 .= ';';
I am making an ordering form and all of the products' data are stored in a MySQL database.
There is a menu page with 10 items, each item has its own drop-down list for quantity (qty).
I am using PHP to generate HTML form elements (eg. input textfields) and display items.
Database has been redesigned: Table1= User_Orders, Table2= Product_Data
All code to display product information and to connect to MySQL, is
working correctly
My display code:
form action="process.php" method="POST" name="menu"
//PHP
$system = 'SELECT * FROM products ORDER BY id ASC';
if(!$result2=mysql_query($system)){
die('Error encountered. MySQL said: '.mysql_error());
}
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty1" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/>
<textarea name="desc1" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu; }
//END PHP, restart HTML
</form >
My Submit Code
//PHP
$submit=$_POST['submit'];
$sitem=$_POST['qty1'];
$sdesc=$_POST['desc1'];
$sql = "UPDATE products SET item='$sitem' ,description='$sdesc' , WHERE `id`='".mysql_escape_string($id)."'";
if($submit) //submit button is pressed
{
mysql_query($sql);
}
Problem:
When I submit the form, only the newest/lastest row is updated (the one with the highest ID). The other fields are unaffected.
My idea to why it is happening:
I notice the textfields all share the same name's. This is because of the PHP generated HTML.
Question:
How do I make each textfield have its own unique name using generated PHP? (eg. qty1, qty2).
My Research
I thought about using an array: qty[]
Something like this:
How to get multiple selected values of select box in php?
http://www.shotdev.com/php/php-form/php-input-multiple-textbox/comment-page-1/#comment-42091
Please help me, I am stuck.
Lee
Either you can use name[] and get the parameters as an array in php
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty[]" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/> <textarea name="desc[]" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}
Or you can append a count to name.
$count = 1;
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty' . $count . '" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/> <textarea name="desc' . $count . '" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
$count++;
}
Ok, first off, you're not passing the item id into the form so it knows what item to actually update.
Let me see what I can do here:
while ($rows2 = mysql_fetch_array($result2))
{
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty[' . $id . ']" type="text" class="textfield" id="qty1" value="'. $gitem .'" size="25"/>
<textarea name="desc[' . $id . ']" cols="10" rows="3" class="textfield" id="desc1" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}
This should return 2 arrays when submitted, qty and desc, with the keys of each entry equal to the id from the DB.
Then when checking the submission:
if($_POST['submit']) //Wanna check this first off, checks whether or not form has been submitted, don't want to do anything at all concerning processing the submission if the form hasn't been sumbitted, probably better to do if(isset($_POST['submit'])) rather than checking directly.
{
$qty = $_POST['qty']; //These two variable declarations assign the two form field arrays into easier to type/identify variable names, might want a little additional error checking to at least make sure that these are arrays with is_array() before going into the foreach loop.
$desc = $_POST['desc'];
//Loop through each entry from the form, UPDATE entries in database that correspond to array keys
foreach($qty as $key => $value) //Set up a loop on the $qty array from the form as array $key and $value and iterate through each entry in the array, the array keys should be the same item id from the DB that corresponds to both qty and desc value entries
{
$sitem = mysql_real_escape_string($value); //Escape $qty[$key] ($value) textfield input from form, put it in an easy to type variable. Note also, mysql_real_escape_string requires an active mysql connection to have been previously established elsewhere. mysql_escape_string() which you were using is depreciated, mysql_real_escape_string() is better.
$sdesc = mysql_real_escape_string($desc[$key]); //Escape $desc[$key] textarea input from form, put it in an easy to type variable. Since the keys should match, you can reach outside the foreach into $desc for it.
$id = mysql_real_escape_string($key); //Escape $key (id) from form, in case of malicious live html editing, might be best to cast to (int) instead like $id = (int)$key since id should always be an int.
$sql = "UPDATE `products` SET `item` = '$sitem', `description` = '$sdesc' WHERE `id` = $id LIMIT 1"; //Construct SQL query from escaped variables. Backticks around field and table names are pretty standard formal syntax. LIMIT 1 speeds up the query and reduces db server load because it will stop when it finds a matching WHERE condition rather than continuing to look for more, and there should only be a single matching id field, so no reason to continue to look for more.
mysql_query($sql); //Execute Query
}
}
Oh, here's the code for doing it with PDO for extra security:
if($_POST['submit']) //Wanna check this first off
{
$qty = $_POST['qty'];
$desc = $_POST['desc'];
$dsn="mysql:dbname=whateveryourdbisnamed;host=localhost"; //Of course change values to appropriate ones
$dbh = new PDO($dsn,"mysqlusername","mysqlpassword"); //Connect to DB. Might want some error checking to make sure it connected.
foreach($qty as $key => $value)
{
$sql = "UPDATE `products` SET `item` = :item, `description` = :desc WHERE `id` = :id LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":item",$value,PDO::PARAM_INT); //Note: Not sure if item is a number of not. If a string of any length, change it to next line
//$stmt->bindParam(":item",$value,PDO::PARAM_STR,128); //Note, change last parameter to set max length of string
$stmt->bindParam(":desc",$desc[$key],PDO::PARAM_STR,256); //Change last parameter to set max length of desc, or remove if no max length
$stmt->bindParam(":id",$key,PDO::PARAM_INT);
$stmt->execute(); //Execute query
}
}
Try...
$i = 0;
while ($rows2 = mysql_fetch_array($result2))
{
++$i;
$id=$rows2['id'];
$gitem=$rows2['item'];
$gdesc=$rows2['description'];
$menu='<input name="qty' . $i . '" type="text" class="textfield" id="qty' . $i . '" value="'. $gitem .'" size="25"/>
<textarea name="desc' . $i . '" cols="10" rows="3" class="textfield" id="desc' . $i . '" style="width: 222px; height: 51px;">'.$gdesc .'</textarea>';
echo $menu;
}
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 :)