I'm trying to update multiple rows using a form and a foreach loop. I've tried solutions found on stackoverflow, but just can't seem to get it to work. I'm working on page project.php?id=13
My HTML form:
<form method="post" action="project.php?id=<?php echo $id; ?>">
<?php while($row = $shops->fetch_assoc()) : ?>
<input type="hidden" name="shop[]" value="<?php echo $row['id']; ?>">
<input type="text" name="boxposition[]" class="form-control" value="<?php echo $row['box_position']; ?>" style="width: 50px;">
<input type="submit" name="update" value="Update Order" class="btn btn-primary">
<?php endwhile; ?>
</form>
My PHP code (on the same page) which is executed on if(isset($_POST['update'])) :
$shopid = $_POST['shop'];
$boxorder = $_POST['boxposition'];
foreach ($shopid as $index => $value) {
$query = "UPDATE shops SET box_position = '".$boxorder[$index]."' WHERE id = '".$shopid[$index]."'";
$update_row = $db->update($query);
Unfortunately, it only updates the first row (lowest id). The very strange thing is that I get the correct values when I echo them using. E.g.:
echo $shopid[$index].'<br>';
echo $boxorder[$index].'<br>';
An example:
I update the $boxorder for 2 rows:
Row 1 (for shop 1): new value = 6 (old value was 7)
Row 2 (for shop 2): new value = 8 (old value was 5)
Using foreach to echo the result, it shows the correct values:
1 (shop id)
6 (new boxorder value)
2 (shop id)
8 (new boxorder value)
What am I missing? Thanks in advance for helping me out!
Try following
<?php while($row = $shops->fetch_assoc()) : ?>
<form method="post" action="project.php?id=<?php echo $id; ?>">
<input type="hidden" name="shop[]" value="<?php echo $row['id']; ?>">
<input type="text" name="boxposition[]" class="form-control" value="<?php echo $row['box_position']; ?>" style="width: 50px;">
<input type="submit" name="update" value="Update Order" class="btn btn-primary">
</form>
<?php endwhile; ?>
to
<form method="post" action="project.php?id=<?php echo $id; ?>">
<?php while($row = $shops->fetch_assoc()) : ?>
<input type="hidden" name="shop[]" value="<?php echo $row['id']; ?>">
<input type="text" name="boxposition[]" class="form-control" value="<?php echo $row['box_position']; ?>" style="width: 50px;">
<input type="submit" name="update" value="Update Order" class="btn btn-primary">
<?php endwhile; ?>
</form>
$shopid = $_POST['shop'];
$boxorder = $_POST['boxposition'];
$query = "UPDATE shops SET box_position =? WHERE id =?";
$db->prepare($query);
foreach ($shopid as $index => $value) {
$db->execute(array($boxorder[$index], $shopid[$index]));
}
This should do it. This way you prepare the statement with ? and fill it inside your for each.
you can do it with also as the following :
$query = "UPDATE shops SET box_position = :position WHERE id = :id ";
$db->prepare($query);
foreach ($shopid as $index => $value) {
$db->execute(
array(
':position' => $boxorder[$index],
':id' => $shopid[$index]
)
);
}
Related
I'm trying to echo a piece of text with PHP nested in it, anyone know how? I've tried it like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" class="form-control" name="new-cat-title">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
}
}
}
It prints: <?php if(isset($cat_title)){echo $cat_title;} ?>
I've tried it like this:
<input value="' . <?php if(isset($cat_title)){echo $cat_title;} ?> . '" type="text" class="form-control" name="new-cat-title">
I'd do it like this (showing only the echo part inside the php code):
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label><input value="';
if(isset($cat_title)){echo $cat_title;};
echo '" type="text" class="form-control" name="new-cat-title"></div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
This echoes the two strings (in single quotes) and in between them the variable depending on the condition, keeping the double-quote pairs of the attribute values intact.
Echo is a php statement. You use it to display an output, as a string. What you need is, replacing echo ' with ?> and </form>'; with </form><?php. These closing(?>) and opening(<?php) tags let you decide which part of your document should be processed as PHP. So PHP will ignore the rest of the document.
Based on Johannes' answer I managed to figure out an answer. I need to close the PHP tags and instead of echoing the wished result, put it in the while loop.
Like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
?>
<input value="<?php echo $cat_title; ?>" type="text" class="form-control" name="cat_title">
<?php
}
}
}
Two tables Order and Line_items are Relate with each other as order_id is placed in line items,
now first populate the order table and then lineitems table on the base of order table's id.
All of the heppening in one isset() has two functions one add values in orders table and second function take order id and then populate the lineitems function.
Problems is for the very first lineitems the order id is "" in Html form's value attribute of order_id. (very hard for me to explain this problem).
Here is my Php isset() function.
if(isset($_POST['check_out'])){
$user_id = $_POST['user_id'];
$shipping_address = $_POST['shipping_address'];
$billing_address = $_POST['billing_address'];
$shipping_method_id = $_POST['shipping_method_id'];
$grand_total = $_POST['grand_total'];
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
$order_id = $_POST['latestorder'];
$product_id = $_POST['product_id'];
$product_price = $_POST['product_price'];
$product_quantity = $_POST['product_quantity'];
$product_total = $_POST['product_total'];
if (empty($order_id)) {
$order_id=$order->latestOrderRecord();
$order_id=+1;
}
$id= count($product_id);
for ($i=0; $i <$id ; $i++) {
$line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]);
// $shoping_cart->
header('location:../cart.php');
}
}
html form
<form method="post" action="n/GetPostData.php" class="woocommerce-shipping-calculator">
<td data-title="Shipping">
Flat Rate:
<span class="amount">$300.00</span>
<p><a data-toggle="collapse" aria-controls="calculator" href="#calculator" aria-expanded="false" class="shipping-calculator-button">Calculate Shipping</a></p>
<div id="calculator" class="shipping-calculator-form collapse">
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<select rel="calc_shipping_state" class="country_to_state" id="calc_shipping_country" name="shipping_method_id">
<option>Select Shipment Method</option>
<?php $shipping_method=$shipment_method->allShipmentMethod();
while ($row=mysqli_fetch_assoc($shipping_method)) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>
</p>
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<input type="text" id="calc_shipping_postcode" name="shipping_address" placeholder="Shipping Address" class="input-text">
</p>
<p id="calc_shipping_state_field" class="form-row form-row-wide validate-required">
<input type="text" id="calc_shipping_postcode" name="billing_address" placeholder="Billing Address" class="input-text">
</p>
</div>
</td>
</tr>
<tr class="order-total">
<th>Total</th>
<td data-title="Total">
<strong><span class="amount">$<?php echo $total; ?></span></strong>
<input type="hidden" name="grand_total" value="<?php echo $total ?>">
<input type="hidden" name="user_id" value="<?php echo $id ?>">
<?php $latestrecord=$order->latestOrderRecord(); ?>
<input type="hidden" name="latestorder" value="<?php echo $latestrecord ?>">
<?php $total=0; $all_cart_products=$shoping_cart->allShopingcartValue($id);
while ($row=mysqli_fetch_assoc($all_cart_products)) { ?>
<input type="hidden" name="product_id[]" value="<?php echo $row['product_id']; ?>">
<input type="hidden" name="product_quantity[]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="product_price[]" value="<?php echo $row['price']; ?>">
<input type="hidden" name="product_total[]" value="<?php echo $row['total']; ?>">
<?php } ?>
<p><button type="submit" class="button" name="check_out" type="submit">Chcek Out</button></p>
</td>
</tr>
</form>
for the very first time when order table is empty the name="latestorder" show "" (no value).
Here is latestOrderRecord() function definition
public function latestOrderRecord()
{
$query="SELECT MAX(id) AS LatestRecord FROM orders";
$conn=$this->Connection();
$result = mysqli_query($conn,$query);
$num_rows = mysqli_num_rows($result);
if ($num_rows>0) {
while ($row=mysqli_fetch_assoc($result)) {
$latestrecord=$row['LatestRecord'];
}
}
return $latestrecord;
}
Issue is that, you are using header() redirection inside your for() loop:
for ($i=0; $i <$id ; $i++) {
header('location:../cart.php'); // that is the issue
}
You must need to use a variable for success in for loop, then you can use it outside the loop for redirection, something like:
HINT:
if($success){
header('location:../cart.php');
exit(); // always use exit() after header() otherwise script execution will not stop
}
Edit:
As per your comment, you are getting order id 0 in lineitem table, because you are inserting $_POST['latestorder'] value which is 0 because you dont have latest ID.
you need to insert the last inserted id of this query:
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
return last inserted id from addOrder() method, and store it into a new variable and use this variable in your lineitem table something like:
$lastInsertID = $order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
and, here $line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]); replace $order_id with $lastInsertID
Make sure, method addOrder() returns last inserted ID.
I'm trying to call the old values to be edited. What part am I wrong at?
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (mysqli_num_rows($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
<a href="viewBook.php?edit=<?php echo $row['BookNo']; ?>" class="edit_btn" >Edit</a>
</td>
<?php
if (isset($_GET['edit'])) { ?>
<form method="post" action = "viewBook.php">
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
<input type="text" name="ISBN" value="<?php echo $ISBN; ?>">
<input type="text" name="title" value="<?php echo $title; ?>">
<input type="text" name="author" value="<?php echo $author; ?>">
<input type="text" name="publisher" value="<?php echo $publisher; ?>">
<input type="text" name="status" value="<?php echo $status; ?>">
<input type="text" name="cost" value="<?php echo $cost; ?>">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>
<?php } ?>
</form>
So far, what it does is, when the user clicks the edit button, it just shows 6 text fields. I thought by doing what I did, it was supposed to show the details already filled in the textbox.
When you do
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
$BookNo is not defined.
maybe you wanted to do something like this:
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$id'");
<form method="post" action = "viewBook.php">
your form method is "post" but you are checking $_GET You must check $_POST
if (isset($_GET['edit']))
you are passing value in $id And using $BookNo which not define.
only 6 input field will be show because first one is using hidden property.
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
when you click on submit button data will be receive by $_POST
i am coding a page for the attendance of students and in the page all the students name are retrieved dynamically from database using while loop and inside the while loop i have used a radio button.
my problem is the radio button work's correctly but i am unable to insert the value of radio buttons into database.here is my code :
include'connection.php';
#$id = mysql_real_escape_string($_GET['id']);
$res=mysql_query("SELECT * FROM `std_register` AS p1 ,`sims-register-course` AS p2 WHERE p2.semester=p1.std_semester and p2.department=p1.std_department and p2.id = '".$id."'");
if ($res==FALSE) {
echo die(mysql_error());
}
while ($row=mysql_fetch_assoc($res)) { ?>
<input type="hidden" id="dept_0" name="dept[]" value="<?php echo $row["department"] ?>">
<input type="hidden" id="course_name_1" name="course_name[]" value="<?php echo $row["course_name"] ?>">
<input type="hidden" id="std_semester_2" name="std_semester[]" value="<?php echo $row["semester"] ?>">
<input type="hidden" id="std_id_3" name="std_id[]" value="<?php echo $row["id"] ?>">
<input type="hidden" id="std_name_4" name="std_name[]" value="<?php echo $row["std_name"] ?>">
<tr>
<td class =info><?php echo $row["std_name"];?></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="1"></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="2"></td>
</tr>
<?php }?>
</table><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" name="submit" value="Assign" class="btn btn-large btn-block btn-primary"></div></div>
</form>
<?php
for ($i=0; $i < 4; $i++) {
if(isset($_POST["submit"])) {
$stdid = mysql_real_escape_string($_POST['std_id'][$i]);
$dptname = mysql_real_escape_string($_POST['dept'][$i]);
$courseName = mysql_real_escape_string($_POST['course_name'][$i]);
$stdSemester = mysql_real_escape_string($_POST['std_semester'][$i]);
$std_name = mysql_real_escape_string($_POST['std_name'][$i]);
$present = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $present;
$insrt = mysql_query("INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$present',0,0)") or die(mysql_error());
}
}
and is it possible to insert values from this radio buttons to two columns of database?
I am not sure but try to add 'checked' property in radio input
<input type="radio" name="<?php echo "status[".$row["std_name"]."]" ?>" value="1" checked></td>
Or
use Select tag instead of radio button
EDIT
use this code to insert in present column or absent column
$value = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $value;
if($value == 1) //check if present
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$value',0,0)";
}
else //if absent
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester',0,'$value',0)";
}
$insrt = mysql_query($sql) or die(mysql_error());
I have made a simple cart, my issue is when I want to update the quantity of a single product. I use the post method to do it. When I add in the quantity on the correct item and click on update, it does the update successfully but any other product their quantity is updated as well. Please help.
<?php
if(isset($_POST['Update']))
{
if(isset($_POST['prod_id']))
{
$myid = $_POST['prod_id'];
if (in_array($myid,$_SESSION['cart']))
{
$key = array_search($myid, $_SESSION['cart']);
$value_qty = "qtyval".$key;
$_SESSION[$key] = $_POST[$value_qty];
$message=$_SESSION[$key];
echo '<script>alert("'.$message.'")</script>';
}
}
}
?>
<?php
foreach ($_SESSION['cart'] as $key_value => $listitem)
{
$sql="SELECT * FROM products where id = '$listitem'";
$result_set = $database->query($sql);
while ($row=$database->fetch_array($result_set)){
?>
<div class="basket_block" id="basket_block">
<div class="item_block_remove" id="item_block_remove">Remove</div>
<div class="item_block" id="item_block">Name: <?php echo $row['Title_of_Message']; ?><br />
Description <?php echo $row['Description']; ?>
</div>
<div class="item_qty" id="item_qty"><form action="" method="POST" enctype="multipart/form-data" name="frmqty">
<input type="text" name="<?php echo (string)'qtyval'.$key_value; ?>" size="3" style="border-radius: 15px;text-align: center;" value="<?php
if(isset($_POST['Update']))
{
echo $_SESSION[$key];
}
else
{
echo $_SESSION[$key] = 1;
}
?>" />
<input type="hidden" name="prod_id" id="prod_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Update" name="Update" style="border:none;cursor:pointer;padding-top:10px; background-color:transparent;" />
</form></div>