Insert Value From One Table to Another on Update MySql, PHP - php

I was wondering if there was a way to take one value from a column in a Table and add it to a column in another table.
The Scenario: I have a table (Shopping_Cart). It stores all of my customers shopping cart items in the columns CustomerID, PID, Price, Status (Status can be "IN_CART" which means it was added and "OPEN" means that it has been paid for and ready to be processed and shipped). Then I have a table (Products). It stores product information in columns PID, Price,Weight`. When My customers place an item in the shopping cart I do not capture the price. Prices can change daily so if they add something today, when they come back tomorrow the price may increase or decrease in their shopping cart. When my customer checks out and payment is confirmed, I am trying to grab the Price in the (Products) table where Products.PID = Shopping_Cart.PID and then apply that price to the Shopping_Cart.Price to lock in that final price since the customer has paid for it. Any Ideas? I got it set up to change the items for that customers cart to "OPEN" but I am a little lost on getting my script to grab a value from one table and applying it to another table. Below is my PHP Script for changing the Lines from "IN_CART" to "OPEN".
if($The_Function=="CLOSE_LINES"){
$cart_close_session_id = $_GET['close_session_id'];
$response = array();
require_once __DIR__ . '/db_connect.php';
//connect to my db
$db = new DB_CONNECT();
$result = mysql_query("UPDATE shopping_cart SET Status = 'OPEN' WHERE SessionID LIKE '$cart_close_session_id' AND Status LIKE 'IN_CART'");
if ($result) {
$response["close_success"] = 1;
//GRAB PRICE FROM "PRODUCTS TABLE" AND UPDATE SHOPPING_CART
}else{
$response["close_success"] = 0;
}
echo json_encode($response);
}

Assuming that you have a *shopping_cart* table with a price and a product_id column, you can update it with the price of the products table, like this:
UPDATE shopping_cart SET price =
(SELECT price FROM products WHERE id = shopping_cart.product_id)

You can join against the products table and update the shopping_cart upon purchase as seen below:
UPDATE shopping_cart c
JOIN products p
ON p.pid = c.pid
SET c.price = p.price
WHERE c.customer_id = ?

Related

PHP Deleting multiple rows with returning values to another table

I have a code here that deletes a single row of data from sales_order and then returns the value of the qty to the products table.
<?php
include('connect.php');
//get values from href
$id=$_GET['id'];
$invoice=$_GET['invoice'];
$qty=$_GET['qty'];
$product=$_GET['product'];
//returns quantity to stock
$sql = "UPDATE products
SET stock=stock+?
WHERE productid=?";
$q = $db->prepare($sql);
$q->execute(array($qty,$product));
//execute query
$result = $db->prepare("DELETE FROM sales_order WHERE transaction_id= :id");
$result->bindParam(':id', $id);
$result->execute();
header("location:pos.php?invoice=$invoice");
?>
Now what I'm aiming to do here is to have a reset button that will delete all rows with the same invoice number from sales_order and then each row returns the quantity value to the products table. I can't seem to find a way to do it. Can anyone help me?
You can do an UPDATE with a JOIN:
UPDATE products AS p
JOIN sales_order AS s on s.productid = p.productid
SET p.stock = p.stock + s.quantity
WHERE s.invoice_number = :invoice
Then you can delete all the sales_order rows with that invoice number. You should use a transaction to ensure that this is all done atomically.
I'm making some assumptions above about the schemas of the tables, you'll need to adjust to your actual column names.
I think you can go with an array concept. I think its simple to retrieve all the required values using select query before deletion. Then you can save it to the required tables. The you can delete the values

How to prevent user from bypassing the quantity using the add button

In my button the user can add more quantity from his order.
What I want is to prevent the user from adding more than the quantity left.
The button goes into the cart table. What I want is to connect the product_qty to the cart so that the user cannot abuse the add button.
E.G. Item A ( 5 stocks left ) , User inputs 4 , but the user can abuse it using the button going from 4 to 8.
my product table consists of
productid,
categoryid,
product_name,
product_price,
product_qty,
supplierid,
my cart table consists of
cartid,
userid,
productid,
qty,
This is my php file
<?php
include('session.php');
if(isset($_POST['add'])){
$id=$_POST['id'];
$query=mysqli_query($conn,"select * from cart where productid='$id'");
$row=mysqli_fetch_array($query);
$newqty=$row['qty']+1;
mysqli_query($conn,"update cart set qty='$newqty' where productid='$id'");
}
?>
You have to first check whether addition of the product exceeds the total stock or not, and then perform the UPDATE operation accordingly.
<?php
include('session.php');
if(isset($_POST['add'])){
$id=$_POST['id'];
$query=mysqli_query($conn,"SELECT * FROM product NATURAL JOIN cart where productid = '$id' AND userid = YOUR_USER_ID");
if(mysqli_num_rows($query)){
$row=mysqli_fetch_array($query);
if(($row['qty'] + 1) <= $row['product_qty']){
$newqty = $row['qty'] + 1;
mysqli_query($conn,"update cart set qty='$newqty' where productid='$id'");
// your code
}
}
}
?>
Sidenotes:
It is not a good idea to call SQL query/submit form for every addition of product. Let user decide the total quantity of the product user wants and then send the accumulated value to database. Use JavaScript for this.
Learn about prepared statement because right now your queries are susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

Checking for record in MySQL and create if not exist

When I click a buy now button I'm checking to see if the record (product id) exists in my mysql database table and if they don't create another one and if they do, just update the existing one.
It creates the first record fine and it even updates when I click it again without making another record, but when I click another product it creates another record and it never updates the following records.
In other words it just updates the first product id and it creates new records for the rest.
here is an image of my table
function add_to_cart(){
global $connection;
$ip = getIp();
if(isset($_GET['add'])) {
$product_id = $_GET['id'];
$product_price = get_item_price($product_id);
$query = "SELECT * FROM cart WHERE ip_address = '{$ip}' ";
$check_query = query($query);
confirm($check_query);
$row = fetch_array($check_query);
$db_product_id = $row['product_id'];
if(mysqli_num_rows($check_query) === 0 || $product_id != $db_product_id) {
$query = "INSERT INTO cart(product_id,ip_address,quantity,price_sum) VALUES('{$product_id}', '{$ip}' ,1, '{$product_price}')";
$send_query_cart = query($query);
confirm($send_query_cart);
redirect("index.php");
} else {
$query = "UPDATE cart SET quantity = quantity + 1, price_sum = price_sum + '{$product_price}' WHERE product_id = '{$product_id}' ";
$update_records = query($query);
confirm($update_records);
redirect("index.php");
}
}
}
Probably the best solution is to create a UNIQUE constraint on (I am assuming) product_id and ip_address.
ALTER TABLE `cart` ADD UNIQUE `unique_index`(`ip_address`, `product_id`);
Then, I would not store the price of items in the cart at all. The price of an item can be looked up in your items table. When an order is completed you can save the price of the individual item since it could change, but while it's in the cart you want the most recent price.
Once you have done that, your query can be simplified to
$query = "INSERT INTO cart(product_id,ip_address,quantity)
VALUES ('{$product_id}', '{$ip}', 1)
ON DUPLICATE KEY UPDATE
quantity = quantity+1";
and you don't even have to check it - the query will handle the update or insert automatically.
Also, I wouldn't rely on ip_address to identify users - if someone is shopping on their phone while riding in a car, it could easily change. Two people on the same router can appear to have the same ip address to your website. I would save something in the session or in a secure cookie and use that to identify them.
To get the totals, you would do something like:
$totals = "SELECT cart.product_id, cart.quantity * products.price as product_price_total
FROM cart
LEFT JOIN products USING(products.id = cart.product_id)
WHERE ip_address = '{$ip}'";

Set Magento Product Group Permissions Programatically

When you edit a Product in Magento there is a Permissions tab with two multi-selects on it.
Disable product for
and
Hide product price for
We need to set the Disable product groups programatically by including 'Mage.php' and using a script to update the Disabled Groups.
For example we want to Disable a product for 10 specific groups for a product. We've been able to do pretty much everything else you can do in the Admin Interface in script so there should be a way to access this using Mage::getModel('catalog/product') or another Model. Call a function, pass in the group ID's you want to set the product to disabled for.
But can't seem to track it down.
Thanks!
Found where the data is stored in the database and just ended up modifying the database directly.
$groupsDisabledArray is an array that contains an ID for each group I want to disable product permissions for. The data in magento is simply stored as a comma separated list of Group ID's
Example:
1,2,3,4,5,6,7,8,9,10
So I implode my disabled group ID's array to get a comma separated list
$groupsList=implode(",", $groupsDisabledArray);
Then either insert or update the catalog_product_entity_text table which is where the value is stored.
The value is stored in catalog_product_entity_text where
entity_id = PRODUCT_ID
attribute_id = 155 (This corresponds to the table eav_attribute where attribute_code = 'aw_cp_disable_product')
entity_type_id = 4 (This corresponds to table eav_entity_type where entity_type_code = 'catalog_product')
store_id = STORE_ID (If you just have one store you should just be able to put 0 here for the Default Store)
Code to do the complete update below. May need to update the path to Mage.php depending where you put your script.
include("/app/Mage.php");
/* Get DB Connections */
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$writeConnection = $resource->getConnection('core_write');
$tableName = $resource->getTableName('catalog_product_entity_text');
/* $groupsDisabledArray - Array of all of the Magento Group ID's I want to disable this product for */
$groupsList=implode(",", $groupsDisabledArray);
$sql="SELECT * FROM $tableName WHERE entity_id=$product_id AND attribute_id=155 and entity_type_id=4 AND store_id=0;";
$results = $readConnection->fetchAll($sql);
if (count($results) > 0) {
$sql="UPDATE $tableName SET value='$groupsList' WHERE entity_id=$product_id AND attribute_id=155 and entity_type_id=4 AND store_id=0;";
}
else
{
$sql="INSERT INTO $tableName (entity_id, entity_type_id, store_id, attribute_id, value) VALUES ($product_id, 4, 0, 155, '$groupsList')";
}
$writeConnection->query($sql);

Copy multiple rows from one table to another, directly in MySQL?

I am trying to copy values directly from one mysql table to another... but the trouble is, there are many rows to copy, so that sub-select statement will return many rows but the param :order_id is just written once.
Given that problem, I'm having trouble figuring out how to write this process:
# 1: Create new Order & Copy the cart basket to the Order basket
$order_id = addOrder($customer_id);
if ($order_id > -1) {
$sql = "INSERT INTO tbl_order_basket(order_id, product_id, product_name,
basket_qty, basket_price, subtotal)
VALUES (:order_id, (SELECT (cart.product_id, product.name,
cart.cart_qty, cart.cart_price, cart.subtotal)
FROM tbl_shopping_cart AS cart
INNER JOIN tbl_product AS product
ON cart.product_id = product.id
WHERE cart.php_sesskey = :session_id)
)
WHERE order_id=:order_id;";
}
Here is the data I'm trying to copy:
ORDER BASKET CART BASKET PRODUCTS
FK order_id FK php_sesskey
FK product_id <-- FK product_id === PK id
product_name <-- <-- name
basket_qty <-- cart_qty
basket_price <-- cart_price # <-- : copy to
subtotal <-- subtotal # === : join on
How should I go about doing this?
Note: I'm using PHP 5 and MySQL 5.5
Maybe you can use this one?
INSERT INTO ... SELECT ... FROM ... WHERE ...
To create the query, first make a SELECT which gives you all the fields which you want to insert. Then prepend INSERT INTO <table> and you're done.
Look into SELECT INTO TABLE
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
Try using the query below; this type of syntax has worked for me in the past. Since there is no WHERE in a MySQL INSERT statement (manual) I have removed that part. Also, do not use the VALUES keyword when doing an INSERT...SELECT (manual).
$sql = '
INSERT INTO tbl_order_basket(order_id, product_id, product_name,
basket_qty, basket_price, subtotal)
SELECT :order_id, cart.product_id, product.name,
cart.cart_qty, cart.cart_price, cart.subtotal
FROM tbl_shopping_cart AS cart
INNER JOIN tbl_product AS product
ON cart.product_id = product.id
WHERE cart.php_sesskey = :session_id)
';

Categories