Foreach loop full execution and stop the rest of the script - php

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*/

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

Auto increment a SESSION key ID

I'm having a problem in doing something.
I have this code snippet to add a product to cart:
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if(!isset($_SESSION['cart']))
{
$product_id_session = 1;
}
else
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price
);
$_SESSION['cart'][$product_id_session] = $columns;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
}
As you can see, if the session cart is created, I assign the variable $product_id_session with the count of SESSION arrays plus one. Otherwise, the variable $product_id_session is set to 1. In the cart page I have a link to remove the selected product:
foreach($_SESSION['cart'] as $product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$product['product_id_session']}'\">
Remove from cart
</button>";
}
Then, in the remove.php file I have this to process the data from Query String and remove the product from the cart:
$product_id_session = isset($_GET['product_id_session']) ? $_GET['product_id_session'] : "";
unset($_SESSION['cart'][$product_id_session]);
The problem I'm facing is: for example, I added two products in the cart. Then I removed the first product and added another product to the cart. The new product, instead of being added, just will replace the product that was previously added in the cart and the $product_id_session will be always the same value. What I'm doing wrong? How to specify an ID for the SESSION?
You can add new items to the cart just with:
$_SESSION['cart'][] = $columns;
Then it will be appended to end of the array.
And, after deleting item from the array, you can (but it is not necessary) re-index it by
$_SESSION['cart'] = array_values($_SESSION['cart']);
When printing out the cart, you just update the foreach loop to catch the key value into some variable, i.e. $index. The difference is in the $index=>$product part.
foreach($_SESSION['cart'] as $index=>$product)
{
echo "<button onClick=\"location.href='remove.php?product_id_session={$index}'\">
Remove from cart
</button>";
}
Remove.php remains basically the same, I just updated it for better readibility:
if (isset($_GET['product_id_session']) and $_GET['product_id_session']) {
$product_id_session = $_GET['product_id_session'];
unset($_SESSION['cart'][$product_id_session]);
}
Instead of trying to create an extra ID to manage your cart you should just rely on the unique product ID already stored in your database :
if($num == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC); // no need for the loop as you only have 1 result
extract($row);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
// keep track of the added product for the time being
if (!isset($_SESSION['cart'][$product_id])) {
$columns = array(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'amount' => 0, //just add last comma as good practise here
);
$_SESSION['cart'][$product_id] = $columns;
}
//raise the amount
$_SESSION['cart'][$product_id]['amount']++;
redirect_to('products.php?&message=added&product_name='. $_SESSION['cart'][$product_id_session]['product_name']);
}
And change the remove accordingly :
foreach($_SESSION['cart'] as $product) {
echo "<button onClick=\"location.href='remove.php?product_id={$product['product_id']}'\">Remove from cart</button>";
}
EDIT :
To keep an "unique" id you should not use count to calculate the ID
Just use an extra variable to keep track of last Id :
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
$_SERVER['cart_product_id'] = 1;
}
else
{
$_SERVER['cart_product_id']++;
$product_id_session = $_SERVER['cart_product_id'];
}

Adjust Array Value in Shopping Cart based on User login state

How would I adjust individual values within the $_SESSION array depending on whether the user is logged_in or not logged_in. So basically the array values equate to the individual item prices within the shopping cart and will be adjusted if the user logs in or logs out of the SESSION.
Here's my current code:
PHP
if(!empty($_SESSION)){
foreach($_SESSION['basket'] as $b){
if ($session->logged_in) { $b['itemprice'] = ""; }
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
MYSQL
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) { }
The closest I've come to getting this to work is each product in the cart is given the same price which changes if the user logs in or out. However, I need each item to change to the new price specific to that items product ID.
Some of our members receive a discount on certain items, so once the user logs in from being a GUEST to the registered USER the price needs to be changed on page refresh.
An example being :
**Logged in == FALSE**
Item 1 Price: 100.00
Item 2 Price: 100.00
**User logs in (Logged in == TRUE)**
Item 1 Price: 85.00
Item 2 Price: 94.00
I hope I've been clear - any advice would be appreciated.
Thanks
OPTION A:
function updateCartPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
while ($result=mysql_fetch_array($query)) {
foreach ($_SESSION['basket'] as $key => $item)
{
if($result['product_id'] == $item['itemid'])
{
$_SESSION['basket'][$key]['itemprice'] = ($_SESSION['logged_in']) ? $result['price'] : $result['price_100'];
}
}
}
}
if(!empty($_SESSION)){
updateCartPrices();
foreach($_SESSION['basket'] as $b){
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) { ?>
// display message informing the user that their cart is empty
OPTION B (performance better):
function getLoggedInPrices()
{
$itemids = array();
foreach ($_SESSION['basket'] as $item) {
$itemids[] = "'" . $item['itemid'] . "'";
}
$itemids_str = implode(',', $itemids);
$query = mysql_query("SELECT product_id, price, price_100 FROM product WHERE product_id IN ($itemids_str)");
$prices = array();
while ($result=mysql_fetch_array($query)) {
$prices[$result['product_id']] = $result['price'];
}
return $prices;
}
if(!empty($_SESSION)){
$loggedInPrices = getLoggedInPrices();
foreach($_SESSION['basket'] as $b){
if($_SESSION['logged_in'])
{
$b['itemprice'] = $loggedInPrices[$b['itemid']];
}
$sub_total = $b['itemprice'] * $b['itemqty'];
$total = $total + $sub_total;
// display contents of shopping cart
}
}
elseif (empty($_SESSION)) {

Json get value from table

I have a small code make this result :
{"nomdupharmacie":[{"pid":"71","name":"dft","longi":"9.010505676269531","lati":"34.1575970207261","matricule":"M65203124"},{"pid":"72","name":"erezrzer","longi":"7.529407627880573","lati":"34.63767601827405","matricule":"123"},{"pid":"73","name":"qsd","longi":"8.83832462131977","lati":"35.172592315800905","matricule":"333"}],"success":1}
with this php code :
// get all products from products table
$result = mysql_query("SELECT *FROM nomdupharmacie") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["nomdupharmacie"] = array();
$v = "12";
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["longi"] = $row["longitude"];
$product["lati"] = $row["latitude"];
$product["matricule"] = $row["personnel_number"];
// push single product into final response array
array_push($response["nomdupharmacie"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
i have to test for example :
$value = "555"
if $value exists in column of matricule so get alert
so the questionis how to make test if the value exists in the Matricule column or not ??
You should look into using PDO or ADOdb instead of mysql_query which is deprecated.
The only option is to compare manually like this:
1) create a function that receives an array x and value v to check
function isMatriculeInArray($x, $v)
{
foreach($x as $z)
{
if($z["matricule"] == $v)
{
return true;
}
}
return false;
}
2) check if matricule is in there
if(!isMatriculeInArray($response["nomdupharmacie"], $v)
{
array_push($response["nomdupharmacie"], $product);
}

check the product is present in session array and if present increase the count value for that product using php

i am adding products to session as array but before adding that product to session how to check that product is present in session array or not.
If the product is present i want to increase the count of that product, if not add that product to session array. My php code is given below.
session_start();
if(empty( $_SESSION['fields1'] )) {
$_SESSION['fields1'] = array();
}
$qty = 1;
$id = $_POST['id'];
$name = $_POST['name'];
$description = $_POST['description'];
$cnt = 0;
print_r($_SESSION['fields1']);
if (! empty($_SESSION['fields1'])){
foreach ($_SESSION['fields1'] as $key=>$val){
if ($id == $val['id']){
$qty = $val['qty']++;
//echo "qty ===".$qty;
$_SESSION['fields1'][$cnt]['qty'] = $val['qty']++;
}
else
{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
$cnt++;
}
}else{
$arrayval = array('id' => $id,'name' => $name,'description' => $description,'qty' => $qty);
array_push($_SESSION['fields1'] ,$arrayval );
}
//print_r($_SESSION['fields1']);
echo json_encode($_SESSION['fields1']);
If $id is ID of product and fields is array of products, try something like this:
if(empty($_SESSION['fields'][$id]))
$_SESSION['fields'][$id]['qty'] = 1;
else
$_SESSION['fields'][$id]['qty']++;

Categories