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>
Related
I've search the forum for the same situation that I have but still couldn't find the solution. It's probably a piece of cake but I can't figure it out why my $_GET[] doesn't work.
I've created a product page and when I add something to the cart I want to display a message. I've made it work with the url in the form action but then my cart counter in the header stops working properly.
If it's possible I don't want to add any extra in the url like a "?success" because then it just keeps adding ?success to the url if I add more to the cart, that works in action but not with header() ?
Here is my code for the product page:
<?php include_once '../header.php';
$message = "";
$product = New Product;
$cart_data = [];
// if the variables are set - run the following statement
if(isset($_POST["addtocart"])) {
if(isset($_COOKIE["cart"])) {
// Removes backlashes and dont replace previous item, gives every item a new row.
$cookie_data = stripslashes($_COOKIE['cart']);
$cart_data = json_decode($cookie_data, true);
}
// Returns the productid and Size in the array
$item_list = array_column($cart_data, 'ProductsId');
$size_list = array_column($cart_data, 'Size');
// Returns the value if the statement is true
if(in_array($_POST["ProductsId"], $item_list) && in_array($_POST['selectedSize'], $size_list)) {
// A foreachloop that repeats the array value of the selected key variable.
foreach($cart_data as $keys => $values) {
if($cart_data[$keys]["ProductsId"] == $_POST["ProductsId"] && $cart_data[$keys]["Size"] == $_POST["selectedSize"]) {
$cart_data[$keys]["quantity"] = $cart_data[$keys]["quantity"] + $_POST["quantity"];
}
}
}
else {
$item_array = array(
'Img' => $Img = filter_var($_POST["Img"], FILTER_SANITIZE_STRING),
'ProductName' => $ProductName = filter_var($_POST["ProductName"], FILTER_SANITIZE_STRING),
'Size' => $Size = filter_var($_POST['selectedSize'], FILTER_SANITIZE_STRING),
'ProductsId' => $ProductsId = filter_var($_POST["ProductsId"], FILTER_SANITIZE_NUMBER_INT),
'Price' => $Price = filter_var($_POST["Price"], FILTER_SANITIZE_NUMBER_INT),
'quantity' => $quantity = filter_var($_POST["quantity"], FILTER_SANITIZE_NUMBER_INT),
);
$cart_data[] = $item_array;
}
$item_data = json_encode($cart_data);
setcookie('cart', $item_data, time() +(3600),'/');
header("location: product-detail.php?product=".$_GET['product']."?success");
}
if(isset($_GET['success'])) {
$message = "Varan lades till i varukorgen";
};
var_dump($message);
?>
<main id="product-content">
<section>
<form method="post" name="cartCount" action="">
<!-- product-detail.php?product=<?php echo $_GET['product']; ?> -->
<?php if(isset($_GET['product'])) {
$product->ProductsId = $_GET['product'];
$product->ProductId = $_GET['product'];
$product->ProductsId = $_GET['product'];
} else {
$product->ProductsId = $_POST['ProductsId'];
}
$result = $product->get_product();
$test = $product->get_productvariation();
while ($row = $result->fetch()) { ?>
<div class="product-card-detail">
<div class="product-image-wrapper">
<img class="product-image" src="../<?php echo $row['Img'];?>" >
<input type ="hidden" name="Img" value="<?php echo $row['Img'] ?>">
<?php $results = $product->get_images();
$Images = $results->fetch();
if(isset($Images['Image'])) { ?>
<img class="product-image" src="../<?php echo $Images['Image'];?>">
<?php } ?>
</div>
<div class="product-details-text">
<h2 class="title"><?php echo $row['ProductName']; ?></h2>
<input type ="hidden" name="ProductName" value="<?php echo $row['ProductName'] ?>">
<span class="price"><?php echo $row['Price'];?> SEK</span>
<input type ="hidden" name="Price" value="<?php echo $row['Price'] ?>">
<span class="select-title">Storlek</span>
<select class="size" name="selectedSize">
<?php while ($sizeRow = $test->fetch()) { ?>
<option>
<?php echo $sizeRow['Size']; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="quantity" value="1" />
<input type="submit" class="addtocart-btn" name="addtocart" value="Lägg i varukorgen"/>
<div><?php echo $message ?></div>
<input type ="hidden" name="ProductsId" value="<?php echo $row['ProductsId'] ?>">
<span class="title-description">Beskrivning</span>
<p class="description"><?php echo $row['Description']; ?></p>
</div>
</div>
<?php } ?>
</form>
</section>
</main>
<?php include_once "../footer.php";?>
I've made a test page that works exactly as expected so I can only think that is has to be something about the url?
Test code:
<?php
$message ="";
if(isset($_POST['submit'])) {
header("location: index.php?success");
}
if(isset($_GET['success'])) {
$message = "hello";
}
var_dump($message);
?>
<form method="post" action="">
<input text name="name" value="">
<input type="submit" name="submit" value="submit">
<?php echo $message ?>
</form>
Glad if anyone can see why it doesn't work!
You have made a mistake:
header("location: product-detail.php?product=".$_GET['product']."?success");
See the above line and notice that you are appending param success with ?.
Make it & as:
header("location: product-detail.php?product=".$_GET['product']."&success");
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
This is my code I want to add one input field for every image preview and save it to db.. the field is coming but I'm not getting any data.. can anyone suggest how can I post them???
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
<ul class="reorder_ul reorder-photos-list" id="previewImg">
<?php
while($row = $fetch_imgid->fetch()):
$delid = $row['id'];
//echo $row['id'].' '.$row['name'].'<br/>';?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle" data-image-id="<?php echo $delid; ?>">
<img src="uploads/<?php echo $row['name']; ?>" alt="">
<input type="submit" class="del_btn" value="Delete Image" />
<input type="text" id="cap" name="cap[]" placeholder="Enter Caption Here" />
<input type="hidden" id="cap_id" value="<?php echo $row['id']; ?>" />
<?php
endWhile;
?>
</ul>
<input type="submit" value="Add Caption" name="addcap" /> <?php include('addcap.php'); ?>
and this is addcap.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if(isset($_POST['addcap'])){
foreach($_POST['cap'])
{
$imgcap = $_POST['cap'];
if($imgcap!=empty())
{
try
{
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$sql=$con->prepare("UPDATE attempt010 SET caption='$imgcap' WHERE id='$cap_id'");
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
}
}
?>
<input type="hidden" id="cap_id" value="<?php echo $row['id']; ?>" />
Must have unique id. You can't send multiple fields with same id. You will get only last one.
For example:
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
<form action="addcap.php" method="post">
<ul class="reorder_ul reorder-photos-list" id="previewImg">
<?php
$id_array="";
while($row = $fetch_imgid->fetch()):
$id_array = $id_array.$row['id'].",";
$delid = $row['id'];
//echo $row['id'].' '.$row['name'].'<br/>';?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle" data-image-id="<?php echo $delid; ?>">
<img src="uploads/<?php echo $row['name']; ?>" alt="">
<input type="text" id="cap_<?php echo $row['id']; ?>" placeholder="Enter Caption Here" />
<?php
endWhile;
$id_array = substr($id_array, 0, -1);
?>
<input type="hidden" id="cap_ids" value="<?php echo $id_array ; ?>" />
</ul>
<input type="submit" value="Add Caption" name="addcap" />
</form>
<!--addcap.php-->
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if(isset($_POST['addcap'])){
if(isset($_POST['cap_ids'])){
$ids_array = explode(",", $_POST['cap_ids']);
foreach($ids_array as $ids)
{
$idcap = 'cap_'.$ids;
$imgcap = $_POST[$idcap];
if($imgcap!=empty())
{
try
{
$con=new
PDO("mysql:host=localhost;dbname=newimg","root","");
$query = "UPDATE attempt010 SET
caption='$imgcap' WHERE id='$ids'";
echo $query;
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
}
}
}
?>
This code looks like it can't work. Because you have submit and form handling code in same page. The idea behind form is to post data to different page(set in form action) and this page will do something with this data and display results to the user. For your example to work make form in your first file like:
<form action="addcap.php">
<inputs here>
</form>
Nowadays it is common that database operations are done asynchronic on server side, when user can continue using the page/app.
So learn how to use jQuery and AJAX. Maybe nodeJS or other new stuff.
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]
)
);
}
I am currently creating a basic CMS for practice purposes and I can't seem to figure out:
How to Update all fields at once AND delete (or upload new) images for each independent record
Any help would be appreciated :)
Updating All Fields Code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$sql = "UPDATE services SET page_title=:pageTitle, event_title=:eventTitle, event_content=:eventContent WHERE id=:id";
foreach ($id as $key => $value) {
$query = $connect->prepare($sql);
$query->bindValue(':pageTitle', $_POST['page_title'], PDO::PARAM_STR);
$query->bindValue(':eventTitle', $_POST['event_title'][$key], PDO::PARAM_STR);
$query->bindValue(':eventContent', $_POST['event_content'][$key], PDO::PARAM_STR);
$query->bindValue(':id', $id[$key], PDO::PARAM_STR);
if ($query->execute()) {
$message = 'Records updated.';
} else {
$message = "Failed to update records. Please contact Administrator.";
}
}
}
PHP/HTML Code:
<form method="post" action="">
<?php
$sql = "SELECT * FROM services";
$query = $connect->prepare($sql);
$query->execute();
$i = 1;
while($results = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<?php if ($i === 1) { ?>
<input type="text" value="<?php echo $results['page_title'] ?>" name="page_title">
<?php } ?>
<div class="service">
<input type="hidden" value="<?php echo $results['id'] ?>" name="id[]">
<input type="text" value="<?php echo $results['event_title'] ?>" name="event_title[]"/>
<?php
if ($results['event_imgSrc'] == '') { ?>
<img src='' style="width:100px; height:100px;">
<?php } else { ?>
<img src="<?php echo '../'.$results['event_imgSrc'] ?>" name="event_imgSrc">
<?php }
?>
<input type="file" name="image">
<input type="submit" name="del_img" value="Delete Image">
<input type="submit" name="upload_new" value="Upload New Image">
<textarea name="event_content[]"><?php echo $results['event_content'] ?></textarea>
</div>
<?php $i++; } ?>
<input type="submit" name="submit" value="Update"/>
<?php if (isset($message)) { ?>
<p><?php echo $message ?></p>
<?php } ?>
</form>