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;
}
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 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();
}
}
I have an array that is created from a mysqli query.
The array then goes through a for loop to display a table.
Within the table there is a form submit that needs to take the selected row and pass the information into a variable to be modified.
I tried to take a screenshot, but I just joined and have no rep. In theory, the user needs to be able to select Modify and the array elements for that row need to pass into text input boxes with a preset value of $row[$j][0] where $j is fixed based on the row selected to modify.
Here is what this part of the code looks like.
if (isset($_POST['Select']) &&
isset($_POST['Search']))
{
$Select = get_post($con,'Select');
$Search = get_post($con,'Search');
if ($Select == "Invalid")
{
echo "<br /><br />Please select a search catagory";
}
else if ($Search == NULL)
echo "<br /><br />Please enter search field";
else
{
$query = "SELECT * FROM table WHERE $Select LIKE '$Search%'";
$result = mysqli_query($con,$query);
if (!mysqli_query($con,$query)) {
die('Error: ' . mysqli_error($con));
}
$rows = mysqli_num_rows($result);
echo "<table id='myTable' class='tablesorter'>
<thead><tr>
<th>Modify</th>
<th>Field1</th>
<th>Field2</th>
<th>etc...</th>
</tr></thead><tbody>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
$modrow[$j] = $row;
echo <<<_END
<tr>
<td><form action="Lookup.php" method="post"><input type="submit" value="Modify" /><input type="hidden" name="submitted" value="$modrow[$j]"</form></td>
<td>$row[0]</td>
<td>$row[1]</td>
<td>etc...</td>
</tr><br />
_END;
}
echo "</tbody></table>";
if (isset($_POST['submitted']))
{
echo <<<_END
<form action="Lookup.php" method="post"><pre>
Field1 <input type="text" name="Field1" size="50" **value="$modrow[$j][0]"** />
...more of the same...
From what I gather, you're wanting to pass a request to the server containing some form of identifier for the row so that you may create a form for users to modify that row's data. Sorry if I misunderstood - I would ask first if I understood you correctly as a comment, but don't have enough rep.
You can use an id to submit to the server.
<button type="submit" name="modify" value="<?= $theRowsId ?>">Modify</button>
Think of the values of name and value attributes as a function/method and value being passed respectively.
Now when Modify is clicked, you can get retrieve the ID, perform a query for the ID and populate the input with the rows data.
$rowId = $_POST['modify'];
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 am trying to update multiple rows here.However I fail to point the right ID of the row.
<?php
$table = 'DynamicPage';
$query = mysql_query(Query::SelectAllFrom($table));
// Count table rows
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
$id[] = $row['ID'];
echo '
<h3>Column name: </h3><input type="text" name="name" maxlength="30" value="' . $row['Name'] . '" />
<h3>Tekst: </h3><textarea type="text" name="fulltext[]" maxlength="2000">' . $row['FullText'] . '</textarea>';
}
echo '<input name="Submit" type="submit" value="Submit" />
</form>';
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
for ($i = 0; $i < $count; $i++) {
$queryUP = mysql_query("UPDATE $table SET Name='" . $_POST['name'] . "' WHERE id='??????????????'");
$result = mysql_query($queryUP);
}
if ($result) {
header("location:index.php");
}
}
?>
So far I can update the first row (if id='1') from the last <h3>Column name: </h3><input type="text" name="name"... I know that I am not passing the ID's in the right way, but I have to idea about the syntax. If anyone has an idea, please let me know :)
Thanks
Perhaps you should add a hidden input field with IDs:
HTML part
<input type="hidden" name="id[]" value="'.$row['ID'].'" />
<h3>Column name: </h3><input type="text" name="name[]" maxlength="30" value="'.$row['Name'].'" />
<h3>Tekst: </h3><textarea name="fulltext[]" maxlength="2000">'.$row['FullText'].'</textarea>';
PHP
for($i=0; $i<count($_POST['ID']); ++$i){
//query goes here
}
SQL QUERY
UPDATE $table SET Name='{$_POST['name'][$i]}', Tekst='{$_POST['fulltext'][$i]}' WHERE id='{$_POST['id'][$i]}'
This is from top off my head, not tested, but should give you an idea.
And of course, escape all the input fields.
Try this after your $_POST['Submit'] isset test:
for($i=0;$i<sizeof($id);$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id = " . $id[$i]);
$result = mysql_query($queryUP);
}
input type="text" ids="id[]" maxlength="30" value="'.$row['id'].'"
//then submit part
for($i=0; $i<count($_POST['id'];$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id='$_POST['id'][$i]'");
$result = mysql_query($queryUP);
}
You may concatenate $row['ID'] and $row['Name'] to create a name you can parse later
<h3>Column name: </h3><input type="text" name="name" maxlength="30"
value="' . $row['ID'] . '_' . $row['Name'] . '" />
then you can use something like:
list($name, $id) = explode($_POST['name'], '_');
** also note you have a security risk using user input directly inside SQL statement