Multiple Rows Update with same form names in PHP - php

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?

Related

PHP Query to UPDATE/DELETE a dynamically generated input field in a table

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";
}
}

How do I list each value from my_sqli_fetch_row?

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;
}

How to check all values present in the column 'pincode'?

This code only reads the first value present in the column. If the value posted in the html form matches the first value, it inserts into the database. But I want to check all the values in the column and then take the respective actions.
For example, if i give input for 'ppincode' and 'dpincode' as 400001, it accepts. but if i gave 400002, 400003,..... it displays the alert even if those value are present in the database
DATABASE:
pincode <== column_name
400001 <== value
400002
400003
400004
...
also i tried this
$query = "SELECT * FROM pincodes";
$result = mysqli_query($db, $query);
$pincodearray = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$pincodearray[] = $row;
}
}
If I understand well - you want to compare value from POST request with all retrieved records saved in DB and if it matches - perform action.
If so, I would recommend using for(each) loop. Example:
if( !empty($row){
foreach( $row as $key ){
if($key['pincode'] == $ppincode && $key['pincode'] == $dpincode){
// your action goes here
}
}
}
Additional tip: use prepared statements :)
SELECT count(*) FROM table WHERE ppincode=ppincode AND bpincode=bpincode
if this return 0 then insert or else show alert.

PHP extract each record in variable for insert

Here is my PHP variable:
$container = $_POST['containerNumber'];
Inside $_POST['containerNumber'], there are multiple container numbers that are retrieved when a user checks a checkbox from a form. That code is not necessary to display. Just know that $_POST['containerNumber'] can have multiple container numbers assigned to it.
What I need to do is extract each container number from the POST so that I can run a mysql INSERT statement per each container number.
In the database table, there are multiple columns, with container_num being the column I'm trying to update (for now).
How can I turn $container into an array and retrieve each container number that has been assigned to the variable?
I know I need to utilize a FOREACH loop. With that said, there will more than likely be multiple INSERT statements that will automatically be created with the loop.
$SQL = "INSERT INTO myTable (container_num) VALUES ('$container')";
// times however many containers the variable $container had stored in it
Please help.
EDIT **
Once the user checks however many checkboxes, I can display each container like this:
<INPUT name="containerNumber" id="containerNumber" class="containerNumber" />
When I do this, it can be displayed to the screen like this:
CONT_ID001, CONT_ID002, CONT_ID003...
I hope this helps.
There are multiple ways of doing this.
1) Give the POST parameters you're sending a name that ends with [], PHP automatically assigns them to an array when parsing the POST data. If you're sending the data from an HTML form, this is an example of how to do it:
<form action="" method="POST">
<label>
First container number:
<input type="text" name="containerNumber[]" />
</label>
<label>
Second container number:
<input type="text" name="containerNumber[]" />
</label>
<input type="submit" />
In PHP you can just do
foreach($_POST["containerNumber"] as $container) {
...
}
(Note that this is a feature of PHP and not portable to other server-side langages. This is NOT part of the HTTP specification.)
2) Separate values using some separator, in PHP use explode() to split it.
3) Send the form as JSON or encode that one field as JSON (if sent from HTML, I suggest using jQUery to do either option, as it's the easiest way) and use json_decode() in PHP to extract the contents.
4) Sevaral other options that may be suitable, depending on what exactly you're doing.
If I get you, you have a $_POST variable with multiple values.
If the content of $_POST['containerNumber'] is CONT_ID001, CONT_ID002, CONT_ID003
You can do this:
$result = preg_split("/, /", $_POST['containerNumber']);
//the result dump will be:
//$result[0] = "CONT_ID001";
//$result[1] = "CONT_ID002";
//$result[2] = "CONT_ID003";
The insert code should looks like to (assuming that you have one column for each number):
$SQL = "INSERT INTO myTable ";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$columns .= "container_$id";
$values .= "'$out'";
if (count($result) < $id+1){
$columns .= ", ";
$values .= ", ";
}
}
$SQL .= "($columns) VALUES ($values)";
If you only have container_num column it should looks like:
$SQL = "INSERT INTO myTable (container_num) VALUES ('";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$values .= $out;
if (count($result) < $id+1){
$values .= ", ";
}
}
$SQL .= "$values')";

php & input checkbox store value of each loop

I have a page that will display the names of people from one data base that is joined with another that tracks when two names are linked. Every thing works fine. However; I cannot make the data or specifically the right user name ($id2u) and a string ($permissions) transfer from the input boxes when the user selects one. The onclick event should then show the data fields as per the permission string. The problem is the displayed info is always the last user in the DB that was ran through the loop. Am trying to get the info to carry forward on the onclick event when a check box is clicked so that their info is displayed.
This is he function to call the display of data.
function display1(type) {document.getElementById("pi").style.display = "none"
document.getElementById(type).style.display = ""}
This is the call to the DB that generated the input boxes for each person.
$result1 = mysql_query('SELECT * FROM level1 LEFT JOIN linkreq ON level1.idnumber = linkreq.idme ORDER BY LEAST(lname, fname) DESC');
for ($i = mysql_num_rows($result1) - 1; $i >= 0; $i--){
if (!mysql_data_seek($result1, $i)){echo "Cannot seek to row $i: " . mysql_error() . "\n";continue;}
if (!($row = mysql_fetch_assoc($result1))) {continue;}
if($_SESSION["idnumber"] == $row['id2u']){
if($row['returnack'] == 0){$id2u = $row['idme']; echo'<font color="#FF6600">*</font> '.$row['title'].' '.$row['fname'].' '.$row['mname'].' '.$row['lname'].' '.$row['suffex'].'<br />';}
else{
$permissions = $row['permissions'];
parse_str($permissions);
$permissions;
$id2u = $row['idme'].' ';
echo '<input type="checkbox" value = " .$id2u. " onClick="display1(\'pi\');"> '
.$row['title'].' '.$row['fname'].' '.$row['mname'].' '.$row['lname'].' '.$row['suffex'].'
<br />';}}}
This is the data that gets displayed onclick(pi) but displays last user not the selected one. Basically if the $id2u variable data would carry over from the check box this would work. As can manually force it by setting $id2u = xxxxxx; just before the query.
$result2 = mysql_query('SELECT * FROM pi WHERE idnumber = "'.$id2u.'"');
for ($i = mysql_num_rows($result2) - 1; $i >= 0; $i--){
if (!mysql_data_seek($result2, $i)){echo "Cannot seek to row $i: " . mysql_error() . "\n";continue;}
if (!($row = mysql_fetch_assoc($result2))) {continue;}
echo '<br>row #'.$row['idnumber'];
if($id2u == $row['idnumber']){echo'...// PRINTS OUT DATA //...}}
</span>
I know this should be in mySQLi but for now just need to get it to work will convert later.
Why don't you use a while() loop ?
$query = mysql_query("...");
while($row = mysql_fetch_array($query))
{
...
}
This always works fine for me :)

Categories