I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. Each category section is a single form with fields that are repeated and named according to what row they belong to. The layout is like this:
Category 1
Unit 1 Update Fields
Unit 2 Update Fields
Unit 3 Update Fields
Submit Button for Category 1
etc.
Each field is named the same thing with the unit number added on the end:
Features1, Features2, Features3, etc.
The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc).
I've got most of this sorted out. However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble. At this point, I'm at a loss. Here is a simplified version of my code:
if (isset($_POST['submit'])) {
$form = $_POST['form']; //save which category we're on in a variable.
for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
$Feature = $_POST['Feature'.$i];
$update = "UPDATE Units
SET Feature ='$Feature'
WHERE ID='$i'";
if (($Feature!=${initialFeature.$i})) {
$updateQuery = mysqli_query($dbc, $update);
}
}
}
How can I make this work? Is there a better way to do this?
The way I would do it is using an array in field names.
<input type="text" name="id[]" value="$foo">
Then on the action page for the form
$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
...//do something here using $id[$i] to select elements in the array
}
I think that is what you're trying to do.
try this
for($i=0; $i<3; $i++)
echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';
if (isset($_POST['go'])) {
$feature = $_POST['feature'];
if(is_array($feature)){
for ($i = 1; $i <= count($feature); $i++) {
$update = "UPDATE Units
SET Feature ='$feature[$i]'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}else{
$update = "UPDATE Units
SET Feature ='$feature'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}
hope this code can solve your problem
Related
I have a Table where user can create row with adding input fields dynamically (combination with jquery). I'm successfully able to insert it into the mysql database.
If users want to edit the added already existing fields, I have an edit page where the values are fetched from the mysql DB and populated again into the dynamically creatable table.
Now there are the below probabilities:-
User only makes minor changes on the existing values. In that case
the table has to be UPDATED with the changed values
User Deletes one/multiple row(randomly selected and as per users wish). So when form submitted the php query should only DELETE that perticular row/s in the DB.
User ADDS another row to the previous existing row values, in that case the php query should UPDATE the previous values and INSERT the newly added row values.
The above sequence is not necessarilly restricted the same order. User can perform all the above three function simultaneously at the same time.
Now my problem is(only for the backend) I'm finding a hard time to frame a php & sql query so as to update to the mysql.
my php
if(isset($_POST['submit'])){
$number1 = count($_POST['item']); //
for($i=0; $i<$number1; $i++){
$item = strip_tags(trim($_POST['item'][$i]));
$description = strip_tags(trim($_POST['description'][$i]));
$unitcost = strip_tags(trim($_POST['unitcost'][$i]));
$qty = strip_tags(trim($_POST['qty'][$i])); // Quantity
$sno = strip_tags(trim($_POST['sno'][$i]));// serial number
//QUERY1 if minor updates to above variable then UPDATE (eg, qty value is changed from 3 to 4)
//QUERY2 if row is deleted then DELETE that particular row from db (eg, sno 3 deleted from the table should DELETE corresponding mysql DB values also)
//QUERY3 if row is added then that particular row values should be INSERT (eg, sno 4 is added which is not in the mysql db. So this has to be INSERTED.)
}
}
Pardon me to have asked such question. I'm wasting a whole lot of time with the above queries unable to execute properly. I only require an idea not necessarily the whole code.
Hope all of you out there would advice me some ideas on how this could be implemented. Thanks for the help in advance. Expecting a positive reply.
NB: Just to remind you again, The front end is a Dynamically ADD/DELETE Input Field table
This sounds like a frontend problem. You need to define how you tell the backend whats happening.
<input name="items[$i][name]" />
This will show up as nice array to loop through in php.
foreach($_POST[items] AS $item){
if( $item['delete'] ){
//delete code
}
}else{
//Insert/Update
}
If you want to delete something simply make the field hidden and add a flag to it.
<input type="hidden" name="items[$i][delete]" value="1" />
<input type="hidden" name="items[$i][id]" />
Thank for the reply, appreciate #ckrudelux and #codefather for their intention to help me.
Although their advise didn't help me to structure my query. So I had a long workaround and found out below solution. I'm posting the solution because I couldn't find any article online when it comes to UPDATE/DELETE a dynamically generated input table.
Hope this would be of help to someone.
So what I did basically is that I took all the values into array.
In my dynamically generated add input table code, I added an <input type="hidden" name="sno[]" value="newrow">. So this will be clubbed with the form post. I'm using the normal html post and not ajax.
now my submit.php has ben changed to below
if(isset($_POST['submit'])){
$productid = $_POST['productd'];// No striptag functions
// due to illustration purpose
// First of all, we need to fetch the querying db table.
// This is required in order to compare the existing row values
// with the posted values
$fetchproduct = $link->prepare("SELECT * FROM product WHERE productid=?");
$fetchproduct ->bind_param('s',$productid);
$fetchproduct ->execute();
$fetchresult = $fetchproduct ->get_result();
$serialnumber=array(); // Assigning array to fetch the primary key: Serial Number
while($row = $fetchresult->fetch_assoc()){
$serialnumber[] = $row["sno"];
}
//Newly Inserted Values
//$_POST['sno'] is taken from the dynamic input field defined earlier in this post.
//Basically what we are doing here is we are comparing (the values
//which have been posted from the primary page) and (values present in the db table).
//The difference will give an array of newly inserted table input field values
$insert = array_diff($_POST['sno'],$serialnumber);
//Deleted Values
// This will Difference those values in the db table and values which are
// deleted from the primary dynamic table page
$delete = array_diff($serialnumber,$_POST['sno']);
$countdelete = count($delete); // Counting how many values have been
// lined up for deleting
//Updated Values
// array_intersect will give us the common values present in both the array.
// This means that there is no deletion or insertion to the dynamic table fields.
$intersect = array_intersect($serialnumber, $_POST['sno']);
$update = array_values($intersect);
$countupdate = count($update);
//INSERT ADDED VALUES TO DB
foreach($insert as $key=>$ivalue){
// ID
if(isset($_POST['id'][$key]) && !empty($_POST['id'][$key])) {
$id = strip_tags(trim($_POST['id'][$key]));
}
// ITEM
if(isset($_POST['item'][$key]) && !empty($_POST['item'][$key])) {
$item = strip_tags(trim($_POST['item'][$key]));
}
// DESCRIPTION
if(isset($_POST['description'][$key]) && !empty($_POST['description'][$key])) {
$description = strip_tags(trim($_POST['description'][$key]));
}
// UNITCOST
if(isset($_POST['unitcost'][$key]) && !empty($_POST['unitcost'][$key])) {
$unitcost = strip_tags(trim($_POST['unitcost'][$key]));
}
// QUANTITY
if(isset($_POST['qty'][$key]) && !empty($_POST['qty'][$key])) {
$qty = strip_tags(trim($_POST['qty'][$key]));
}
// AMOUNT
if(isset($_POST['amount'][$key]) && !empty($_POST['amount'][$key])) {
$amount = strip_tags(trim($_POST['amount'][$key]));
}
// INSERT INTO THE DATABASE
$inserttable = $link->prepare("INSERT INTO product (productid, item, description, unitcost, qty, amount) VALUES(?,?,?,?,?,?)");
$inserttable->bind_param('ssssss', $id, $item, $description, $unitcost, $qty, $amount);
$inserttable->execute();
if($inserttable){
header( 'Location:to/your/redirect page.php' ) ; // NOT MANDADTORY, You can put whatever you want
$_SESSION['updatemsg'] = "Success";
}
}
//UPDATE EXISTING VALUES TO DB
for($j=0; $j<$countupdate; $j++){
// ID
if(isset($_POST['id'][$j]) && !empty($_POST['id'][$j])) {
$uid = strip_tags(trim($_POST['id'][$j]));
}
// ITEM
if(isset($_POST['item'][$j]) && !empty($_POST['item'][$j])) {
$uitem = strip_tags(trim($_POST['item'][$j]));
}
// DESCRIPTION
if(isset($_POST['description'][$j]) && !empty($_POST['description'][$j])) {
$udescription = strip_tags(trim($_POST['description'][$j]));
}
// UNITCOST
if(isset($_POST['unitcost'][$j]) && !empty($_POST['unitcost'][$j])) {
$uunitcost = strip_tags(trim($_POST['unitcost'][$j]));
}
// QUANTITY
if(isset($_POST['qty'][$j]) && !empty($_POST['qty'][$j])) {
$uqty = strip_tags(trim($_POST['qty'][$j]));
}
// AMOUNT
if(isset($_POST['amount'][$j]) && !empty($_POST['amount'][$j])) {
$uamount = strip_tags(trim($_POST['amount'][$j]));
}
// UPDATE THE DATABASE
$updatetable = $link->prepare("UPDATE product SET item=?, description=?, unitcost=?, qty=?, amount=? WHERE sno=?");
$updatetable->bind_param('ssssss', $uitem, $udescription, $uunitcost, $uqty, $uamount, $update[$j]);
$updatetable->execute();
if($updatetable){
$_SESSION['updatemsg'] = "Success";
}
}
//DELETE VALUES FROM DB
foreach($delete as $sno){
$deletetable = $link->prepare("DELETE FROM product WHERE sno=?");
$deletetable->bind_param('s', $sno);
$deletetable->execute();
if($deletetable){
$_SESSION['updatemsg'] = "Success";
}
}
}else {
$_SESSION['updatemsg'] = "Error";
}
}
I have two sql statements.
1 lists all columns from my table using mysqli_fetch_assoc
The other statements returns a row where id = specific id using mysqli_num_rows
My problem is that with the mysqli_fetch_assoc, I'm able to use something like:
$rowz['Field'] and it returns the value for every single column name. This is perfect, but, I am unable to get every single value in my row as well. In other words, My code lists all fields: id / name / phone... but when I use myqli_fetch_row, it returns the value for just one column over and over. So every field will just show '193' which is the id. I want all fields to show proper value instead of just the same value from one column over and over.
// listing all columns from table
$sql2 = ("SHOW COLUMNS FROM articles");
$result55 = mysqli_query($link, $sql2);
echo'<form action="update.php" method="POST">';
if (mysqli_num_rows($result55) > 0)
{
// to fetch row of specific id
$sql = "SELECT * FROM articles WHERE ID='".$id."'";
$result5 = mysqli_query($link, $sql);
if (!$result5) {
echo 'no';
}
$row = mysqli_fetch_row($result5);
while($rowz = mysqli_fetch_assoc($result55)){
$z = 0;
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
}
}
echo' </form>';
The issue is the name of the input field, where I have '.$row[$z].' it just keeps returning 0 from array which is just the ID column. Hence why I just keep getting 193 over and over. However, the $rowz['Field'] works much better and loops every single time for each existing column. I hope to get: id = 193, name = john, phone = 123-3345 etc.. But instead I get: id = 193, name = 193, phone = 193.
Please send help!
$z is your column index. and it should be your counter, if you want to generate each column values.
$z = 0;
while($rowz = mysqli_fetch_assoc($result55)){
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z + 1;
}
You have declared $z=0 inside the while loop.
Rather you have to declare it before the while loop and increment it inside the loop.
You have used $z as the index for $row which indicates the specific column of the result obtained from the query.
When you fix it to 0, it means that the first column value only is getting accessed.
$row = mysqli_fetch_row($result5);
$z=0;
while($rowz = mysqli_fetch_assoc($result55))
{
echo '
<input class="form-control" type="text" name="'.$rowz['Field'].'"
value="'.$row[$z].'" />';
$z = $z +1;
}
I am allowing user to create up to ten categories using text boxes in a form. To do this I have ten textboxes in the form with name = cat[]. The first time they enter categories--however many, up to ten, on the receiving end, I just collect the array of categories and save them to a table of categories using an insert statement. So far so good.
However, now I want to let them change categories they already set or add extras up to ten total. The categories they already set have ids. So I echo the ids to the form along with the category names. My problem is how do I collect the names and ids now? New ones need to be inserted and existing ones may need to be updated in the table? For some reason, I'm at a total loss how to do this. This is what I have so far>
Table Cats
id | catname | userid
Form page:
//retrieve existing cats if any...also get catids
echo '<form action = storecats.php method=post>';
$i=1;
//Get all existing cats
while($row = mysql_fetch_array($res))
{
$catname = $row['catname'];
$catid = $row['id'];
echo '<input type = "text name="cat[]" value="'.$catname.'">Cat 1';
echo '<input type="hidden" name="id[]" value = "'.$catid.'">';
$i = $i+1;
}
//empty boxes up to ten.
while($i <= 10){
echo '<input type="text" size=18 name="cat[]" value=""> Cat '.$i.'<br>';
$i = $i+1;
}//end appending of blank categories
echo '<input type="submit" name="submit" value="submit"></form>';
On receiving end, I can collect the array for cat and id.
$idarray = $_POST['id']; //there will be as many elements as there were ids
$catarray = $_POST['cat']; //there will be ten elements in array
Where there is an id, I want to perform an update whereas where there is no id I want to insert unless the value is blank.
My problem is I can't figure out how to link the id and the cat names being received in the different arrays. Note, there will always be ten cat names but there will only be as many ids as were in the table for that user previously.
You can do it with 2 array on HTML side:
$x=0;
while ($row = mysql_fetch_array($res))
{
echo '<input type="text" name="updateCat['.$row["id"].']" value="'.$row["catname"].'"> Cat Name';
$x++;
}
// new ones
for(;$x<10;$x++)
{
echo '<input type="text" name="newCat[]">';
}
and on php side:
// update old categories
foreach ($_POST["updateCat"] as $key => $value)
{
mysql_update ("UPDATE table SET name = $value WHERE id = $key");
}
// insert
foreach ($_POST["newCat"] as $value)
{
mysql_update ("INSERT INTO table {...}");
}
You have also check that there are not more than 10 Categories when inserting new ones.
Name the inputs which are for existing categories cat_update[] and name inputs which are for new categories cat_insert[]. When you process the form data with PHP you have three arrays:
$ids = $_POST['id']; // Ids for update
$update = $_POST['cat_update']; // Values for UPDATE
$insert = $_POST['cat_insert']; // Values for INSERT
for($i = 0; $i < count($ids); $i++) {
//Execute 'UPDATE `table` SET `value` = $update[$i] WHERE `id` = $ids[$i]
}
for($i = 0; $i < count($insert); $i++) {
//Execute 'INSERT INTO `table` (`value`) VALUES ($insert[$i])
}
I'm not sure I get it, but you could simply give different names to the two sets of categories.
In your second loop putting 'name = "new_cat[]"' will allow you to distinguish between modified categories ('$_POST[cat]') and new ones to be inserted ('$_POST[new_cat]') in your receiving storecats.php code.
I'm getting caught up on PHP again, and have the following update code. This works, but only for the last one inserted? I need to update for all gritem id's. I thought adding the [] to a form field that is not unique allows PHP to parse it as an array, but it still sees it as one field?
My HTML I have:
<input type="hidden" name="gritemid[]" value="<?PHP echo $row2['gritemid']; ?>">
<input type="text" name="grqty[]" id="grqty[]" value="" />
The Following PHP code
if(isset($_POST['storageloc']))
{
//Set the GRQTY to subtract from the Orderqty on each item in the list if selected
// find out how many records there are to update
$size = count($_POST['gritemid']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$gritemid= $_POST['gritemid'][$i];
$grqty= $_POST['grqty'][$i];
if ($grqty > "0") {
// do the update and print out some info just to provide some visual feedback
$query = "UPDATE gr_items SET orderqty = orderqty - $grqty WHERE gritemid = '$gritemid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
}
++$i;
}
mysql_close();
First of all, you really should do some validation/sanitisation of your post vars before dropping them into a query. As both the vars you are using appear to be integers I would suggest using intval() -
// define each variable
$gritemid = intval($_POST['gritemid'][$i]);
$grqty = intval($_POST['grqty'][$i]);
If you replace your call to mysql_query() with print($query); do you see the multiple queries that you would expect?
Hi all
Now is 2 week that i searching for an answer to my problem and no luck. hope somone can help me on this
i have a chackbox option that i call from the database
<form style="margin-top:-30px" method="POST" action="extradata.php">
<?php
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > $i) {
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
print "<input type='checkbox' name='extra[]' value='$NA'></td>";
$i++;
}
?>
What i trying to do is to pass the value to extradata.php with 2 value
1.$NA,
2.$PR
when selected box then insert to the database the value of $NA to ex_tra and $PR to ex_price
the extradata.php
<?php
require_once 'library/config.php';
$id=$_POST['pd_id'];
$ssid=$_POST['ct_session_id'];
$total=$_POST['tot'];
$name=$_POST['basedes'];
$qty=$_POST['ct_qty'];
$extra_array = $_POST['extra'];
if ( $extra_array > "0" ) {
foreach ($extra_array as $one_extra) {
$source .= $one_extra.", "; }
$extra = substr($source, 0, -2);
} else {}
$result=mysql_query("INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ex_tra, ex_tra2, ex_price, ct_date) VALUES ('$id','$qty','$ssid','$extra','$name','$total', NOW())");
?>
Best regard to all
Sending two values in one variable is bound to get messy. I would just send the id and get the corresponding values from the database again in extradata.php.
If you really want to send multiple values, I would use fixed indices for the checkboxes (not extra[] but extra[SOME_NUMBER] and add a hidden field next to it (extra_pr[SOME_NUMBER]?) to pass the second value.
Note that you have to use fixed indices as unchecked checkboxes donĀ“t get posted but all hidden fields will get posted.