add to cart using session ( delete ) php - php

How to delete specific item using session array. I've tried many time but my code still cant work. Can anyone help me to check my Code?
As the Remove Cart hyperlink pass the Product id that going to be delete.
but it cannot delete anyway. i have no idea where the error is .
cart.php
if (isset($_POST['lol']))
{
if (isset($_SESSION['cart']) === FALSE) { $_SESSION['cart']=array(); }
$proid=$_REQUEST["proid"];
array_push($_SESSION['cart'],$proid);
}
$total=0;
if (isset($_SESSION['cart']))
{
$total = 0;
foreach($_SESSION['cart'] as $proid )
{
$results = mysqli_query($con,"Select * from product where Product_ID = '$proid'");
$myrow = mysqli_fetch_array($results);
$price = $myrow['Product_Price'];
$total =$total + $price;
?>
<li class = "cartlist"><?php echo '<img src="data:image/jpeg;base64,' . base64_encode($myrow['Product_Pic']) . '" width="196" height="120">';?
><p><span style = "font-weight: bold; font-size: 1.2em;">
<?php echo $myrow["Product_Name"];?></span></br />
RM <?php echo $myrow["Product_Price"];?></br />
<?php echo $myrow["Product_Size"];?>MB <br/>
Remove From Cart</p> </li>
<?php
}
}
?>
<?php
if (isset($_GET['proid']))
$proid=$_REQUEST["proid"];
else
$proid = 1;
if (isset($_GET['action']))
$action =$_REQUEST['action'];
switch ($action)
{
case "remove" :
if (isset($_SESSION['cart']['$proid']))
{
$_SESSION['cart']['$proid']--;
unset($_SESSION['cart']['$proid']);
}
break;
case "empty" :
unset ($_SESSION['cart']);
break;
}
?>

The problem here is that you do not understand how arrays work in php.
Everything you store in an array is a key => value pair, even if you don't esplicitly set a key, php will set an integer value for you.
At some point you add a product id in your cart, like this:
array_push($_SESSION['cart'],$proid);
this can also be written like this:
$_SESSION['cart'][] = $proid;
(And if you look at array_push in the php documentation, it says it's best to write it this way)
This is an assignment, you are adding an element to the array, without specifying the key.
And here:
foreach($_SESSION['cart'] as $proid )
you are looping through the array values, ignoring the keys.
These lines of code suggest that the cart array will look like this:
array(
0 => 'id-for-product-one',
1 => 'id-for-product-two'
);
When you are trying to remove a product from the array, instead you are trying to look for the product as if that id you previously assigned as a value is now the key:
if (isset($_SESSION['cart']['$proid']))
This line has actually two mistakes.
The first is that by using single quotes the value of the string '$proid' is actually $proid. If you want to pass the value contained in $proid you can just omit the quotes, or in case you are building a more complex string you want the doublequotes (or use the . operator for string concatenation).
The second is that there is no array key for $prodid.
Given an array $a = array('key' => 'value') if you want to get 'value', you write $a['key'], what you are doing there is $a['value'].
The solutions here are two:
One is to assign the id both as a key and as a value.
The other is to use array_search to get the key of the element you want to remove and work from there.

Related

Get specific array value where another value is "1"?

I have an array that looks like this:
Id = "ADA001"
Stock: 15
The array has about 1700 records that looks the same, how would I search the array for the ID 1 and return the stock?
Edit: I will need to access the stock of each one of these 17000 records
Edit: I have been getting some help from Daniel Centore, he told me to set an arrays primary key to the id of the item and that it is equal to the stock, but I can't get it to work.
I am currently getting the data from an MySQL database and I store it in an array, like so:
$data[] = array();
$getdisposabletest = mysqli_query($connect, "Select id, disposable FROM products");
while ($z = mysqli_fetch_array($getdisposabletest)) {
$data = $z;
}
Now when I use Daniels code that looks like this:
$myMap = [];
foreach($data as $item) {
$myMap[$item['id']] = $item['disposable'];
}
It doesn't return anything when I try to echo my product with the ID "ADA001"
echo $myMap["ADA001"];
Also when I do "count($mymap)" it says its 2 records big, when it should be muuuch larger than that?
Thanks for help
I would use array_filter. Return the result of a comparitor.
$results = array_filter($targetArray, function($el) {
return $el === 1;
});
Edit: Now that it has been made clear that the OP wants to query from thousands of items, the correct way to do this is to make the Id the key to a map in PHP, like this:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item['Stock'];
}
Now, whenever you want to access item '12', simply use $myMap['12'].
The reason this is faster is because of something called algorithmic complexity. You should read about Big-O notation for more info. Essentially, the first operation here is on the order of n and then looping through each of the items that comes out is on the order of n*log(n), so the final result is on the order of n*log(n) which is the best you'll be able to do without more information. However, if you were only accessing one element, just accessing that one element via MySQL would be better because it would be on the order of log(n), which is faster.
Edit 2: Also notice that if you were to access mutliple fields (ie not just the stock) you could do the following:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item;
}
And simply access item 12's stock like this: $myMap['12']['stock'] or its name like this: $myMap['12']['name'].
You would do something like this.
$newArray=[];
foreach($array as $item){
if($item['Id'] === 1){
$newArray[] = $item;
}
}
$stockArray = array_column($newArray,'Stock');

Get value from multi-dimensional array using variable

I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}

Accounting for missing array keys, within PHP foreach loop

I'm parsing a document for several different values, with PHP and Xpath. I'm throwing the results/matches of my Xpath queries into an array. So for example, I build my $prices array like this:
$prices = array();
$result = $xpath->query("//div[#class='the-price']");
foreach ($result as $object) {
$prices[] = $object->nodeValue; }
Once I have my array built, I loop through and throw the values into some HTML like this:
$i = 0;
foreach ($links as $link) {
echo <<<EOF
<div class="the-product">
<div class="the-name"><a title="{$names[$i]}" href="{$link}" target="blank">{$names[$i]}</a></div>
<br />
<div class="the-image"><a title="{$names[$i]}" href="{$link}" target="blank"><img src="{$images[$i]}" /></a></div>
<br />
<div class="the-current-price">Price is: <br> {$prices[$i]}</div>
</div>
EOF;
$i++; }
The problem is, some items in the original document that I'm parsing don't have a price, as in, they don't even contain <div class='the-price'>, so my Xpath isn't finding a value, and isn't inserting a value into the $prices array. I end up returning 20 products, and an array which contains only 17 keys/values, leading to Notice: Undefined offset errors all over the place.
So my question is, how can I account for items that are missing key values and throwing off my arrays? Can I insert dummy values into the array for these items? I've tried as many different solutions as I can think of. Mainly, IF statements within my foreach loops, but nothing seems to work.
Thank you
I suggest you look for an element inside your html which is always present in your "price"-loop. After you find this object you start looking for the "price" element, if there is none, you insert an empty string, etc. into your array.
Instead of directly looking for the the-price elements, look for the containing the-product. Loop on those, then do a subquery using those nodes as the starting context. That way you get all of the the-product nodes, plus the prices for those that have them.
e.g.
$products = array();
$products = $xpath->query("//div[#class='the-product']");
$found = 0 ;
foreach ($products as $product) {
$products[$found] = array();
$price = $xpath->query("//div[#class='the-price']", $product);
if ($price->length > 0) {
$products[$found] = $price->item(0)->nodeValue;
}
$found++;
}
If you don't want to show the products that don't have a price attached to them you could check if $prices[$i] is set first.
foreach($links AS $link){
if(isset($prices[$i])){
// echo content
}
}
Or if you wanted to fill it will dummy values you could say
$prices = array_merge($prices,
array_fill(count($prices), count($links)-count($prices),0));
And that would insert 0 as a dummy value for any remaining values. array_fill starts off by taking the first index of the array (so we start one after the amount of keys in $prices), then how many we need to fill, so we subtract how many are in $prices from how many are in $links, then we fill it with the dummy value 0.
Alternatively you could use the same logic in the first example and just apply that by saying:
echo isset($prices[$i]) ? $prices[$i] : '0';
Hard to understand the relation between $links and $prices with the code shown. Since you are building the $prices array without any relation to the $links array, I don't see how you would do this.
Is $links also built via xpath? If so, is 'the-price' div always nested within the DOM element used to populate $links?
If it is you could nest your xpath query to find the price within the query used to find the links and use a counter to match the two.
i.e.
$links_result = $xpath->query('path-to-link')
$i = 0
foreach ($links_result as $link_object) {
$links[$i] = $link_object->nodeValue;
// pass $link_object as context reference to xpath query looking for price
$price_result = $xpath->query('path-to-price-within-link-node', $link_object);
if (false !== $price_result) {
$prices[$i] = $price_result->nodeValue;
} else {
$prices[$i] = 0; // or whatever value you want to show to indicate that no price was available.
}
$i++;
}
Obviously, there could be additional handling in there to verify that only one price value exists per link node and so forth, but that is basic idea.

Creating an array from textarea

I am trying to put some data into Amazon's simpledb. I need to enter multiple values for an attribute (comma separated), but as I have the script now it's entering all the values as one attribute. I think I need to create an array from the comma separated values in the textarea, but I don't know how to do that. Heck, I don't really know how to ask this question correctly. :)
Here's the code.
<?php require_once('./simpledb/config.inc.php'); ?>
<html>
<body>
<h1>Input Cities</h1>
<?php
$domain = "states";
if (!empty($_POST["state"])) { // if a value is passed from the key input field save it
$state = $_POST["state"];
} else {
$state = "";
}
$state = stripslashes($state); // remove PHP escaping
if (!empty($_POST["cities"])) { // if a value is passed from the key input field save it
$cities = $_POST["cities"];
} else {
$cities = "";
}
//$cities = stripslashes($cities); // remove PHP escaping
?>
<FORM ACTION="addcities.php" METHOD=post>
<label>State (Caps)</label><br>
<input type=text name="state" size=10 value="<?php echo $state; ?>"><br>
<label>Cities ('' & comma seperated)</label><br>
<textarea name="cities" cols=60><?php echo($cities); ?></textarea><br>
<INPUT TYPE=submit VALUE="Add Cities">
<?php
if (!class_exists('SimpleDB')) require_once('./simpledb/sdb.php');
$sdb = new SimpleDB(awsAccessKey, awsSecretKey); // create connection
$item_name = $state;
//$input_cities = array("value" => array($cities));
echo "<p>putAttributes() item $item_name<br>";
//$putAttributesRequest["make"] = array("value" => "Acura"); // Example add an attribute
$putAttributesRequest['City'] = array("value" => array("Blue","Red")); // Add multiple values
The previous line is the manual way of adding your multiple values into the attribute. I tried doing the following, which gets the value of the text area, but as I mentioned earlier it just creates one value that's comma seperated vs. multiple values.
$putAttributesRequest['City'] = $input_cities; // Add multiple values
The following is just the rest of the code.
$rest = $sdb->putAttributes($domain,$item_name,$putAttributesRequest);
if ($rest) {
echo("Item $item_name created");
echo("RequestId: ".$sdb->RequestId."<br>");
echo("BoxUsage: ".$sdb->BoxUsage." = " . SimpleDB::displayUsage($sdb->BoxUsage)<br>");
} else {
echo("Item $item_name FAILED<br>");
echo("ErrorCode: ".$sdb->ErrorCode."<p>");
}
?>
Use php explode function
For example:
$cities = explode(",", $_POST['cities']);
This will only work if your data is formatted like so:
New York,Las Vegas,Sydney,Melbourne,London
Change the first part of the explode function to match the formatting of your text area.
You can then do something like:
foreach ($cities as $key => $val){
echo trim($val) . '<br />';
}
Put your SimpleDB stuff inside the foreach loop above and use $val where you want to use the city name.
This will loop through the array and do the SimpleDB stuff on each city.
Explode the string on the commas.
$citiesArray = explode(",", $cities);
You'll then want to trim each of the cities to make sure there's not additional white space before or after the city name.
call_user_func_array("trim", $cities);
There is one more Request Parameters in PUT - Replace. Although its default value is false, please specify it as a false. If Replace is false the value will be added as a multi-value to that attribute and if it is true then it will replace the older value.
Also you need to add single pair of 'Attribute Name and Attribute value' each time in PUT request. i.e if you need multvalue V1 & V2 of Attribute A then in you request it would be like this -
https://sdb.amazonaws.com/
?Action=PutAttributes
&Attribute.1.Name=A
&Attribute.1.Value=V1
&Attribute.2.Name=A
&Attribute.2.Value=V2
&Attribute.3.Replace=false
&AWSAccessKeyId=[valid access key id]
&DomainName=MyDomain
&ItemName=Item123
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-01-25T15%3A03%3A05-07%3A00
&Version=2009-04-15
&Signature=[valid signature]

Foreach value from POST from form

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need

Categories