How to insert stock quantity and update into another table? - php

I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?
<?php
include 'db_connection.php';
if(isset($_POST["submit4"])){
foreach($_POST['fk_product'] as $index => $searchid){
$sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal=$_POST['quantity_bal'];
if($quantity_bal==0){
$sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal!=0){
$sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
$query = mysqli_multi_query($conn,$sql);
if($query){
header("location:product.php");
}
}
}
?>

What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this
foreach($_POST['fk_product'] as $index => $searchid){
$sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal = $_POST['quantity_bal'];
if($quantity_bal == 0){
//I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
$sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal != 0){
$sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
}
We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $

Related

I want to update the stock in the database upon clicking submit, but it stores a wrong input

Here is my code to insert the checked values from checkbox to database. I intend to update the stock from another table after I click submit, but it stores an incorrect input. For ex: If I entered 5 quantity on checkout page, instead of decreasing the number of stock, it inputs a negative value of what I entered: -5.. What seems to be the problem here?
<?php
include 'config.php';
$invoice = $_POST['invoiceid'];
if(isset($_POST['submit'])){
$checked_array=$_POST['prod'];
foreach ($_POST['prodname'] as $key => $value) {
if(in_array($_POST['prodname'][$key], $checked_array)){
$product=$_POST['prodname'][$key];
$price= $_POST['price'][$key];
$qty= $_POST['qty'][$key];
$amtpaid = $price * $qty;
$query = "INSERT INTO purchasedproducts SET invoice_id='$invoice', productname='$product', quantity='$qty', amtpaid='$amtpaid'";
$run = mysqli_query($link,$query);
//select product_stock table
$stock_table = mysqli_query($link, "SELECT * FROM product_stock");
$stock = $row['qty_stock'] - $qty;
$update_que = "UPDATE product_stock SET qty_stock='$stock' WHERE product_name='$product'";
$run_update = mysqli_query($link,$update_que);
}
}
}
header('Location: sample.php');
?>
Your query is updating the column value with your "input". What you are wanting is something like this.
$update_que = "UPDATE product_stock SET qty_stock=qty_stock+'$stock' WHERE product_name='$product'";
This is setting the value to its original value plus the input.

Inventory count of my database keeps starting at 28?

I am new to coding and in my code and i am having trouble updating my database.
I am using mysql and php to create a shopping cart that updates inventory when an item is purchased. The cart takes the product id of the item and stores it using the GET array. The problem is that after someone purchases an item, the inventory doesn't adjust probably in my database. the inventory count always starts at 28 every time I purchase an item instead of starting at the proper inventory amount. The code for the shopping cart is:
require 'connect.php';
require 'item.php';
if(isset($_GET['id'])){
$result = mysqli_query($con, 'select * from products where
id='.$_GET['id']);
$products = mysqli_fetch_object($result);
$item = new Item();
$item->id = $products->id;
$item->name = $products->name;
$item->price = $products->price;
$item->quantity = 1;
$_SESSIONS['id']=$_GET['id'];
// Check if the products exists in the cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart); $i++)
if($cart[$i]->id==$_GET['id'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $item;
else{
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
// Delete products in cart
if(isset($_GET['index'])){
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
if(array_key_exists('submit2', $_POST))
{
$results = mysqli_query($con, "select * from products");
$sql="";//init
while($products=mysqli_fetch_object($results)){
for($i=0; $i<count($cart); $i++){
$idcart=$cart[$i]->id;
$quantity= $products->quantity;
$cartquantity = $cart[$i]-> quantity;
$sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';";//u need this to append the query
session_destroy(); }//end for
}//end while
if ($con->multi_query($sql) === TRUE) {//use multi_query
header("location: thankyou.php");
} else {
echo "Error updating record: " . $con->error;
}
$con->close();
I believe the problem is in this code here. $sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';";. Any help will be appreciated. Thank you!
The whole logic around updating the cart quantities seems to be unusual. You have a loop which loops over all of the products and then updates a somehow related database record based on the id from the cart with the quantity from the product. There is no attempt to match the quantity from the product ID with the ID from the cart.
This code just loops through the cart and reduces the quantity of the matching product for each row, it also prepares the statement before the loop and just executes it once for each row...
if(array_key_exists('submit2', $_POST))
{
$sql = "UPDATE products
SET quantity = quantity - ?
WHERE id= ?";
$stmt = $conn->prepare($sql);
foreach ( $cart as $item ){
$stmt->bind_param('ii', $item->quantity, $item->id );
$stmt->execute();
}//end foreach
session_destroy();
}//end if
You could use the quantity values directly in update
$sql = "UPDATE products SET quantity= quantity - ? WHERE id= ? ;"
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $cartquantity, $idcart, );
$stmt->execute();
You forgot to concatenate your multi query sql on the line with this code:
$sql= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
Please put concat operator like this:
$sql .= "UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
Or like this:
$sql= $sql."UPDATE products SET quantity='$quantity' - ".$cartquantity." WHERE id='$idcart';"
I noticed you are executing your update SQL after loop which is fine but without concatenation you are only executing the last query in your loop.

update certain table column if else query

I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.

How to UPDATE all rows in SQL with one query?

I have an existing DATABASE of Prestashop, and I have made small modifications to it. I made a separate PHP page which gets data from table with products (only the data i need) and shows me all products that ARE IN THAT TABLE, one after another. I also have a function which updates a products, on which i press EDIT.
So, in a simple words i can update a single product per click. But now I have about 220 products, and in order to update a value (price) for each product, now, i must click EDIT for each product, 220 times.
Is there a way to make a query in order to update all rows after i click a BUTTON?
Bellow I will show you some basic parts from my script:
GET function:
<?php
$strSQL = "SELECT * FROM ps_product";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
while($objResult = mysql_fetch_array($objQuery))
{
?>
<!-- HTML CODE -->
<? } ?>
UPDATE function for each product
if($_POST["hdnCmd"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .="id_product = '".$_POST["txtEditid_product"]."' ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .=",active = '".$_POST["txtEditactive"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
$_POST["hdnEditid_product] is the product id value that is taken from table.
Please help me to understand how to make a similar **UPDATE function** **which will update all rows (product_id) at once?
As an example i must work around this code:
if($_POST["UPDATEALLPRODUCTS"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
but what I must add/change here:
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
To update all rows to the same value run this query
UPDATE ps_product_shop SET price='".$_POST["txtEditprice"]."';
NOTE: Every records in ps_products_shop will get the same value in price.
How about this ?
Make an array like this : id => price, and then :
$prices = array(
1=>300,
5=>180,
...
);
foreach ($prices as $id => $price) {
$query = "UPDATE ps_product_shop SET price='".$price."' WHERE
id_product='".$id."' ";
mysql_query($query);
}
One way to do it, if you insist on using a single query:
<?php
$product_updates = array("1" => "500", "2" => "1299.99");
$sql_query = "UPDATE my_database.products SET price = CASE id ";
foreach ($product_updates as $key => $value) {
$sql_query .= "WHEN '$key' THEN '$value' ";
}
$sql_query .= "END;";
mysql_query($sql_query);
?>
I am assuming that the page already has the updated price / info that you need and therefore it is just plucking the php variables out
UPDATE ps_product_shop SET price
= CASE
WHEN id_product= $id_product_1
THEN '$edited_price_1'
WHEN id_product = $id_product_2
THEN '$edited_price_2'
Without seeing the form structure it is hard to see what would be the correct variable names but hopefully you can take the code and go with it, i have to do something similar and have PhP autobuild the query using this method

Keeping a counter

*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)

Categories