Foreach update sql loop don't create loops - php

I have some strange problems with this codes:
The while loopp that contains a form inside
<?php
$sql = "SELECT * FROM sessions WHERE SES = '$SES' ORDER BY ID DESC";
$preorders = mysql_query($sql);
while ($pre = mysql_fetch_array($preorders)) { ?>
<tr>
<td class="center">
<form id="update" action="update" method="post">
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
</form></td>
</tr>
<?php } ?>
The submit button
<button type="submit" form="update">Update</button>
Process page
foreach ($_POST['ID'] as $key => $ID) {
$QTY = $_POST['QTY'][$key];
mysql_query("UPDATE sessions SET QTY= '$QTY' WHERE ID = '$ID' ");
}
THE ISSUE
That foreach update only the first item. Mostly, I need to update more than one item. Where is the problem?
Thank you so much!

There are multiple things going wrong with your code. First you use [] in this input's name:
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
and this input as well:
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
You probably want to place them inside <?php ... ?> tags.
Second. You only have one update button but multiple forms. Each form needs its own update button which needs to be included inside each <form> element.
Third. You're using the deprecated mysql functions. Change to mysqli or PDO.
Fourth. You should use Prepared Statements for your update query or else your code is susceptible to SQL Injection.

Related

PHP foreach executing code multiple times

At the bottom of this code you'll see an 'Accept Offer' button, when I click on that another piece of code gets executed as you can see on the bottom of this post.
For example this project has 3 bidders, so 3 times bidder_id and writer_bid so I use 'foreach' and load it in divs, works fine, but now I need to store those variables in a database, which technically works but it doesn't store the bids from the row I pull them from, it just takes the data from the last row, that is if I place the code at the bottom of this thread in my header.
However when I put it inside the loop it executes three times, I saw that when I got an error message that I had to close 3 times cause there are 3 rows in the database table that I pull the data from.
How can I prevent this, and either have it load once when the code is inside the foreach loop, or have it pull the correct writer_bid and bidder_id to store.
<div class="WB-Bottom-block lefts">
<?php $getBidders=" AND project_id=$project_id"; $bidders=getBidder($getBidders); foreach($bidders as $bidder) {
$bidder_id=$bidder['writer_id'];
$writer_bid=$bidder['writer_bid'];
?>
<div class="findwriters_boxes">
<div class="findwriters_right">
<div style="float:right;margin-top:6px;width:170px;">
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="bidder_id" id="bidder_id" value="<?php echo $bidder_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</div>
</div>
</div><?php } ?>
Below the code that needs to be executed and that results in issues, whether I place it inside the foreach loop, or inside the header instead.
As you can see I tried to store it in input fields so that it stays there so the header can pull it on refresh of the page / click of the button.
<?php if(isset($_POST['todo']) && $_POST['todo']=='submit_project') {
$balance=get_client_balance_info($current_user->ID);
$writer_bid=$_POST['writer_bid'];
$bidder_id=$_POST['bidder_id'];
if($balance >= $_POST['writer_bid']) {
global $wpdb;
$sql3="UPDATE `wp_project` SET `writer_id` = '".$bidder_id."' WHERE `id` =". $project_id;
$wpdb->query($sql3);
$sql4="UPDATE `wp_project` SET `price` = '".$writer_bid."' WHERE `id` =". $project_id;
$wpdb->query($sql4);
$sql5="UPDATE `wp_project` SET `status` = '2' WHERE `id` =". $project_id;
$wpdb->query($sql5);
$success_msg="You accepted a bid, the money will be deducted from your account.";
}
else $fail_msg="Your balance is not sufficient.";
I think you should make a form for each div that you are adding right now you are putting the bidder_id in the different inputs but the same name.
So it will get the last inputs, maybe it's better to specify the inputs with the row id or to separate the forms or make the input names as array.
I hope this helps you.
I fixed it with the help of Diar Selimi like this:
<div style="float:right;margin-top:6px;width:170px;">
<form action="" name="frmeditor" method="post" id="frmeditor" >
<input type="hidden" name="todo" id="todo" value="submit_project" />
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="writer_id" id="writer_id" value="<?php echo $writer_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</form>
Before that my form and value="submit_project" tags were scattered all over the place!

Add multiple entries to mysql database through php form

I'm creating a database system to house and retrieve invoices for a retailer/ company. I'm looking for a way to add multiple entries to a mysql database through a php form without having to add each item individually. My form looks like;
<div class="new_invoice">
<form action="addCustomerInvoice.php" method = "post" enctype= "multipart/form-data">
<fieldset>
<legend> Add new invoice for <?php echo $rsCustomer['forename']; echo ' '; echo $rsCustomer['surname']; ?></legend>
<h4>Invoice Number:</h4>
<input type="text" name="invoice_no">
<h4>Item Quantity:</h4>
<input type="text" name="quantity">
<h4>Item Name:</h4>
<input type="text" name="item_name">
<h4>Item Category:</h4>
<input type="text" name="item_category">
<h4>Manufacturer:</h4>
<input type="text" name="item_manufacturer">
<h4>Item Description:</h4>
<input type="text" name="item_description">
<h4>Item Price:</h4>
<input type="text" name="item_price">
<h4>Item Information:</h4>
<input type="text" name="item_info">
<input type="submit" value="Add new record">
</fieldset>
</form>
</div>
And process like;
<?php
include 'database_conn.php';
$InvoiceNumber = $_POST['invoice_no'];
$Quantity = $_POST['quantity'];
$ItemName = $_POST['item_name'];
$ItemCat = $_POST['item_category'];
$ItemMan = $_POST['item_manufacturer'];
$ItemDesc = $_POST['item_description'];
$ItemInfo = $_POST['item_info'];
$sql = "INSERT INTO hlinvoicetable (invoice_no, quantity, item_name, item_category, item_manufacturer, item_description, item_info) VALUES ('$InvoiceNo', '$Quantity', '$ItemName', '$ItemCat', '$ItemMan', '$ItemDesc', '$ItemInfo')";
$queryresult = mysqli_query($conn,$sql) or die(mysqli_error());
echo "New invoice added.
mysqli_close($conn);
?>
I'm wondering is there a way to repeat the form and have it add a new entry to the database unless fields are left blank and it is therefore ignored and no rows are added? Also could all items added hold the same primary key (invoice_no)?
Thanks in advance!
You need to use array names on your inputs. For example:
<input type="text" name="invoice_no[]">
...
<input type="text" name="invoice_no[]">
Then in PHP you would obtain the values from $_POST['invoice_no'][0], $_POST['invoice_no'][1], etc.
You could loop over the values, like:
foreach ($_POST['invoice_no'] as $key => $invoice) {
if (!empty($_POST['invoice_no'][$key])
&& !empty($_POST['quantity'][$key])
&& !empty($_POST['item_name'][$key])
//... include all fields that can't be left empty
) {
// Do insert
}
}
Also, as mentioned above, make sure to use bound parameters instead of putting user-supplied data directly into the SQL queries. It is really not much extra code and is necessary to save you from SQL injection attacks.

PHP Delete record from database MySql

I need to delete a record, in this case a categories from my forum, from the database based on its id.
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" value="<?= ['cat_id']; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
}
?>
</td>
<?php
}
?>
i cant get a "good" way to do it... :(
EDIT: This is for a programming lesson not a real forum!!
Your HTML Input Field needs a name so it can be identified by your PHP.
Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.
Another thig you want to do is read up onj the dangers of SQL injections.
If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way.
Nontheless, try this:
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
{
?>
<td>
<form method="post">
<input type="hidden" name="hid_catid" id="hid_catid" value="<?php echo $cat_id; ?>">
<input type="submit" name="submit" value="Remover" />
</form>
<?php
if(isset($_POST['submit']))
{
$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
}
?>
</td>
<?php
}
?>
--> hidden field should have name and id to use
--
Thanks
Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?
<form method="post">
<input type="hidden" name="cat_id" value="<?= $cat_id ?>">
<input type="submit" name="submit" value="Remover" />
</form>
Then your query has to look like this to correctly grab the id from the post.
mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));

Trying to update dates in database with dynamically created forms

So i've created an administration page that creates X-number of forms based on how many users we have in our database, each of which have a submit button next to them to submit changes to the dates we have in our DBs. My problem is that when I want to get the value of what gets posted I can't extract exactly what I need from what gets posted. It gets saved into an array called and when I print_r the array I get exactly what I want, which is:
[1] => "whatever date they typed in"
(obviously the 1 changes depending on which item they changed the date of)
I need be able to query my datebase by:
UPDATE users SET subdate="whatever they typed in" WHERE id="the array reference number"
I know exactly what I need to do, I'm just not as familiar with SQL as i'd like to be, so any help would be greatly appreciated. Thanks in advance.
Code for reference:
<div class="form-section grid12" id="changedates">
<h1>Change Dates</h1>
<?php
$query = mysql_query("SELECT * FROM users WHERE admin='y'");
?>
<table>
<?php
while($row = mysql_fetch_assoc($query)) {
?>
<tr>
<td>
<h5><?php echo $row['displayname'];?></h5>
</td>
<td>
<form action="" method="POST">
<input type="text" name="subdate[<? echo $row['id'] ?>]" value="<?php echo $row['submissiondate'];?>">
<input type="text" name="nextupdate[<? echo $row['id'] ?>]" value="<?php echo $row['nextupdate'];?>">
</td>
<td>
<input type="submit" value="Set Date" name="setdate">
</form>
</td>
<?php
}
?>
</table>
</div>
You could use foreach...
foreach ($_POST[nextupdate] as $rowId => $time)
{
// do db update
}
Edit: Just realised you have more than one input per form.
Why not name each input with an array name:
<input type="text" name="form_data[<?= $row_id ?>][subdate]">
<input type="text" name="form_data[<?= $row_id ?>][nextupdate]">
In PHP:
foreach ($_POST[form_data] as $rowId => $values)
{
$subdate = $values[subdate];
$nextupdate = $values[nextupdate];
// do SQL stuff
}

how to update mysql with inputs and checkboxes

and with this form: (select * from mp3 aktif = '0')
<form name="form" method="post">
<input readonly type="text" name="id" value="<?=$haciosman['id']?>" />
<input type="text" name="baslik" value="<?=$haciosman['baslik']?>
<input type="checkbox" name="secilen[]" value="<?=$haciosman['id']?>">
<input type="submit" name="onay" value="Onayla" />
I can set "aktif to 1" for each row that i checked. but i want to update "baslik" too! how can i update each "baslik" with that php code?
If I understand you correctly you want to do this:
mysql_query("UPDATE mp3
SET
aktif = '1',
baslik = '" . mysql_escape_string($_POST['baslik']) ."'
WHERE id = '$zuha'");
But this is similar to what you already have in your original question:
mysql_query("update mp3 set aktif = '1',
baslik = '$_POST[baslik]'
where id = '$_POST[id]'")
The only difference now is that you make the query in a loop and use a different ID variable.
My comments on your code in your original question stay the same. ( ;) )
P.S.: Introduced mysql_escape_string() for a little security.
UPDATE: Ok I think I got your problem now. You basically want to create an input field collection for every entry in your database, something like this:
<form name="form" method="post">
<table>
<?php while($haciosman = ($query)):?>
<tr>
<td><input readonly type="text" name="id" value="<?=$haciosman['id']?>" /></td>
<td><input type="text" name="baslik[<?php echo $haciosman['id'] ?>]" value="<?=$haciosman['baslik']?> </td>
<td><input type="checkbox" name="secilen[]" value="<?=$haciosman['id']?>">
</tr>
<?php endwhile; ?>
</table>
<input type="submit" name="onay" value="Onayla" />
</form>
You just define another the names of the text fields as arrays baslik[$haciosman['id']], similar as you did for the checkboxes but this time you specify the array key which is the ID of the record.
Then you PHP code you can access this array ($_POST['baslik'] contains an array now) like this:
if (isset($_POST['onay'])) {
foreach ($_POST['secilen'] as $zuha) {
$olay = mysql_query("UPDATE mp3
SET
aktif = '1',
baslik = '" . mysql_escape_string($_POST['baslik'][$zuha]) ."'
WHERE id = '$zuha'");
}
}
UPDATE 2:
You should really read the official short introduction to forms, follow the links in this article and in general read the official documentation to get more insight in how to work with PHP.

Categories