Comparing from textbox to database - php

Please help me. I'm having trouble in comparing
How do I compare the quantity that was inserted from the stocks from the database
<?php
session_start();
include_once("config.php");
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
$sel = mysql_query("SELECT * FROM products");
$product_stock = mysql_fetch_assoc($sel);
//limit quantity for single product
if($product_qty > $products['stock'])
{
die('<div align="center">Not enought quantity<br />Back To Products.</div>');
}

Your error is in this line:
if($product_qty > $products['stock'])
What is $products['stock']? Above you defined the MySQL result like that:
$product_stock = mysql_fetch_assoc($sel);
So, did you mean?
if($product_qty > $product_stock['stock'])
Also, your code is vulnerable to redirection-attacks: https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards
You need to make sure that you somehow validate the parameter return_url, by allowing only a valid list of URLs. Better would be:
$valid_urls = array(1 => 'http://link1.com', 2 => '...');
And then:
$return_url_param = (int)$_GET["return_url"];
$return_url = isset($valid_urls[$return_url_param] ? $valid_urls[$return_url_param] : 'http://defaulturl.com');

You are comparing $product_qty from wrong variable . Try change $products['stock'] to $product_stock['stock'].
Corrected block of code:-
<?php
//add item in shopping cart
if (isset($_POST["type"]) && $_POST["type"] == 'add') {
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
$sel = mysql_query("SELECT * FROM products");
$product_stock = mysql_fetch_assoc($sel);
//limit quantity for single product
if ($product_qty > $product_stock['stock']) {
die('<div align="center">Not enought quantity<br />Back To Products.</div>');
}
}

Related

Why doesn't my shopping cart count products of the same type?

This is the code so far.
I know its not very secure for injections, I'll take care of that later.
but my problem is that my cart adds product but sometimes i get the:
Unsupported operand types in E:\HostingSpaces\Knoppers1\topjop.nl\wwwroot\portal\core\tj_functions.php on line 358
error and i can't add multiple items of the same type.
line 358: $_SESSION['cart'][$uid] += 1;//
Maybe some of you know because other related questions didn't helped me.
function toevoegen(){
session_start();
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if(isset($_GET['add'])) {
$info = 'U heeft een product toegevoegd <META HTTP-EQUIV=REFRESH CONTENT="1; URL=http://topjop.nl/portal/winkelmandje.php">';
$uid = 0; //update id
foreach($_SESSION['cart'] as $id => $data){
if($data[0]==$_GET['add']){
$uid = $id;//
}
}
if($uid == 0){
array_push($_SESSION['cart'],array($_GET['add'],1));//
}else{
$_SESSION['cart'][$uid] += 1;//
}
}
else {
$info = '';
}
return $info;
}
function winkelmandje(){
mysql_connect("mysql8.mijnhostingpartner.nl","","");
mysql_select_db("Knoppers1_portal");
session_start();
$mand = '<table id="winkelmandje_tabel"><tr><td>Product</td>
<td>Stukprijs</td><td>Aantal</td><td>Totaal bedrag</td><td></td></tr>';
foreach($_SESSION['cart'] as $data){
$id = $data[0];//
$value = $data[1];//
if($value>0){
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$totaal = $get_row['price']*$value;
$totaalprijs = number_format($totaal,2,',','.');
$mand .= '<tr><td>'.$get_row['name'].'</td>
<td>€'.$get_row['price'].'</td><td>'. $value .'</td> <td>€'.$totaalprijs.'</td></tr>';
}
}
else{
}
}
$aantal = '';
$kosten = '';
return $mand.'<tr><td><b>Totaal:</b></td><td></td><td><b>'. $aantal .'</b></td><td><b>'. $kosten .'</b></td></tr></table>';
}
toevoegen = ADD<br>
winkelmandje = SHOPPINGCART
Seems like $_SESSION['cart'][$uid] is an array containing id and value as you read it like that in the follwoing snippet:
$id = $data[0];//
$value = $data[1];//
it seems $_SESSION['cart'][$uid] is an array. so you can't do +=1
maybe do
$_SESSION['cart'][$uid][1] += 1; // increment $value

php session update product if id already in the session

The following function is on carts page, after a user has added product from previous product page. The problem is I need the multidimensional array just to update quantity in cart for same product code being added.
Can someone help me add an if statement so when the same productcode is added quantity increases?
Like this answer however my add to cart is different. PHP Sessions shopping cart: update product if it's already id the session
function AddToCart()
{
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : '';
$itemcount = isset($_SESSION
['itemcount']) ? $_SESSION['itemcount'] : 0;
{
$i = array_search($_POST['productcode'], $cart[PRODUCTCODE]);
$cart[PRODUCTCODE] [$itemcount] = $_POST['productcode'];
$cart[PRODUCTNAME] [$itemcount] = $_POST['productname'];
$cart[QUANTITY][$itemcount] = intval($_POST['quantity']);
$cart[PRICE][$itemcount] = $_POST['price'];
$itemcount = $itemcount + 1;
if(strlen($error) == 0) {
$_SESSION['cart'] = $cart;
$_SESSION['itemcount'] = $itemcount;
}
return $error;
}
Try this.
//check for an existing match
$found = FALSE;
if($cart){
$idx = 0;
foreach($cart[PRODUCTCODE] as $idx => $product){
if($product == $_POST['productcode']){
$found = TRUE;
break;
}
}
}
//if we found a match
if($found){
$cart[QUANTITY][$idx] += intval($_POST['quantity']);
}
//otherwise add new item
else{
//your other code here
}

Foreach loop full execution and stop the rest of the script

I have a product table from where I am checking that quantity for respective product id(s) is valid or not..
this is the code snippet :
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
}
}
/*rest of the code outside the loop*/
So here what is happening is it checks the quantity ($quantity_rem) from table of a product id and if that quantity is less than the quantity given ($q), then the script stops and echo the product id..
But I have more that 1 product .. It's not checking the rest since whenever there is a fault it stops and echo out. I want to check all the products and echo out the product id(s) and stop the rest of the script outside the loop..
Help needed!
Thanks.
and please don't talk to me about sql injection because i know it is vulnerable and i will take care of that..
Try this:
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
$errors = array();
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
$errors[] = $array;
}
}
echo json_encode($errors);
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
$array = array();
if($quants > $quantity_rem){
$array[$ps]['errquant'] = 'wrong_quant';
// note little change - you will get array with product ids as key
//and qty error assigned to them
}
echo json_encode($array);
exit; /*stop the rest of the code from executing*/

Getting product weight in magento

I'm trying to make a csv export script, for a partener price aggregation sistem. i'm having trouble extracting the weight of the products from magento.
$show_prodweight = (#$_GET['weight'] == "on") ? "on" : "off";
....
$product = Mage::getModel('catalog/product');
$product->setStoreId($storeId);
$product->load($product_id);
$prod_model = $product->getSku();
$prod_id = $product->getId();
$prod_name = $product->getName();
if ( $show_prodweight =="on") {
$prod_weight = $product->getWeight ();
}
else {
$prod_weight == "2";
}
....
print $PRODUCT['prod_weight'] . $datafeed_separator .
Can someone please tell me what i am doing wrong ?
resolved it by simplyfing code
$product = Mage::getModel('catalog/product');
$product->setStoreId($storeId);
$product->load($product_id);
$prod_model = $product->getSku();
$prod_id = $product->getId();
$prod_name = $product->getName();
$prod_weight = $product->getWeight();

Substract Session[cart] QUANTITY to STOCK QUANTITY in db

I have a table wich show the ($_SESSION['cart'] with a form inside where I can introduce manually the quantity I want into my ($_SESSION['cart'] PRODUCTS.
<form name="formulario2" method="POST" target="oculto"><input type="hidden" name="action" value="update">
foreach($_SESSION['cart'] as $product_id => $quantity) {
echo "<td align=\"center\"><input type = \"text\" size=\"1\" name=\"qty[$product_id]\" value =\"{$_SESSION['cart'][$product_id]}\"></td>";
}
</form>
Then I use the following to update the ($_SESSION['cart']) quantity
<?php
if(isset($_POST['action']) && ($_POST['action'] =='update')){
//
foreach ($_POST['qty'] as $product_id=> $quantity){
$qty = (int)$quantity;
if ($qty > 0){
$_SESSION['cart'][$product_id] = $qty;
}
}
}
?>
Now I would like to SUBSTRACT those quantities I have UPDATED to the ($_SESSION['cart']) to the quantities in STOCK in my data base.
I think that in the last "foreach ($_POST['qty']" I should also say to substract the QUANTITY UPDATED to the DATA BASE QUANTITY but I dont know how to do it. ANY HELP?
1) Replace value =\"{$_SESSION['cart'][$product_id]}\" with value =\"{$quantity}\". You have it already retrieved in the foreach statement.
2) For the database, having that you use mysql, I would reccommend accessing the database with PDO (I have rewritten your second block of code due to its lack of indentation and not matching parentheses):
<?php
if ((isset($_POST['action']) && ($_POST['action'] == 'update'))
{
foreach ($_POST['qty'] as $product_id => $quantity)
{
$qty = intval($quantity);
$pid = intval($product_id); // ALSO use the intval of the $product_id,
// since it was in a form and it can be hacked
$_SESSION['cart'][$pid] = $qty; // NOTE: you need to also update the
// session`s cart with 0 values, or
// at least to unset the respective
// product:
// unset($_SESSION['cart'][$pid])
if ($qty > 0)
{
// now update the DB:
$mysql_host = "127.0.0.1";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "myShop";
$dbLink = new PDO("mysql:host=$mysql_host;dbname=$mysql_database;charset=utf8", $mysql_user, $mysql_password, array(PDO::ATTR_PERSISTENT => true));
$dbLink->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$query = $dbLink->prepare("update `products` set `stock` = `stock` - ? WHERE `productId` = ? limit 1");
$query->execute(array($qty, $pid));
}
}
}
?>
Hope it works for you!
Regards!

Categories