Acessing $_SESSION in PHP - php

I'm creating an Inventory system in PHP
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$sql = mysqli_query($mysqli, "SELECT * FROM booklists WHERE book_id='$item_id' LIMIT 1");
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row["book_name"];
When I echo my $_SESSION using this
print_r($_SESSION["cart_array"]);
I added 2 item in the cart with the quantity of 1 and 55
Array (
[0] => Array ( [item_id] => 37 [quantity] => 1 )
[1] => Array ( [item_id] => 32 [quantity] => 55 )
)
I wanna update all of the [quantity] values in my session. how do you think I can achieve it ?

The question isn't overly clear, as I don't know what the quantity needs updating by, but to update each quantity, you could do something like this.
foreach($_SESSION['cart_array'] as $index => $item){
// Add 1 to each quantity
$_SESSION['cart_array'][$index]['quantity']++;
}
// Or...
$increaseBy = 5;
foreach($_SESSION['cart_array'] as $index => $item){
// Increase by a fixed amount.
$_SESSION['cart_array'][$index]['quantity'] += $increaseBy;
}
// Or...
foreach($_SESSION['cart_array'] as $index => $item){
// Increase by a random number between 5 and 15.
$_SESSION['cart_array'][$index]['quantity'] += rand(5, 15);
}
// Or...
foreach($_SESSION['cart_array'] as $index => $item){
$increaseBy = $this->getQuantityIncrease($item['item_id']);
$_SESSION['cart_array'][$index]['quantity'] += $increaseBy;
}
// Or...
// By using references.
foreach($_SESSION['cart_array'] as $index => &$item){
$increaseBy = $this->getQuantityIncrease($item['item_id']);
$item['quantity'] += $increaseBy;
}

You can try something like this in your loop,
foreach ($_SESSION["cart_array"] as $key => $item) {
$_SESSION['cart_array'][$key]['quantity'] = 13; // set the qty you want
}

You can use a foreach loop to do this.
$newQuantityValue = 10;
foreach($_SESSION['cart_array'] as $key => $value){
$_SESSION[$key]['quantity'] = $newQuantityValue;
}
All we do here is assign a new value for our quantity and then use a foreach loop to iterate through the $_SESSION variable so that we can update each of your quantity fields with our new value (in this case 10).
For more information about foreach loops, check out the the PHP Docs
Pass By Reference:
You could equally change the value by passing it by reference like this:
$newQuantityValue = 10;
foreach($_SESSION['cart_array'] as $key => &$value){
$value['quantity'] = $newQuantityValue;
}
Because we are passing it by reference, there is no longer any need to reference the $_SESSION
From the docs:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
As a side note:
You could dispense with the $newQuantityValue variable all together and instead just put the number into the loop like this:
foreach($_SESSION['cart_array'] as $key => $value){
$_SESSION[$key]['quantity'] = 10;
}

Related

How to count array in foreach

My Code is :
foreach ($suratmasuk as $key => $h) {
$suratkeluar = $this->db->query("SELECT * FROM surat_masuk WHERE lampiran LIKE '%$h->surat_id%'")->row_array()['suratmasuk_id'];
echo count($suratkeluar);
}
The result is :
11
But i want the result is :
2
Because there are two data in the array. How is it? Pls help me
Get the echo count($suratkeluar); out of the loop. Now you create an array for each iteration and count the elements of that array. So the result is 1 and 1 -----> 11
Try following
$suratkeluar = array();
foreach ($suratmasuk as $key => $h) {
$suratkeluar[] = $this->db->query("SELECT * FROM surat_masuk WHERE lampiran LIKE '%$h->surat_id%'")->row_array()['suratmasuk_id'];
}
echo count($suratkeluar);
If you return data object you need to make this
echo count( array() $suratkeluar );
count() not working with data object

Magento get product ids from orders separated by comma

I need to get productID(s) from an order and display this way:
[1234, 7534, 4587]
I am able to get the product IDs this way:
$incrementId = "12345";
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$items = $order->getAllItems();
$itemcount= count($items);
$meuproduto = array();
$i=0;
foreach($items as $itemId => $item) {
$meuproduto[$i]['id'] = $item->getProductId();
echo implode(", ", $meuproduto[$i]);
}
For example this order had products 2709 and 7048, so I would like to display:
[2709, 7048]
But with the code I have it's showing:
27097048
I have tried str_replace("", ", ", $meuproduto[$i]);, but I get same result. I tried different ways, but always with same result.
print_r($meuproduto[$i]);
results:
Array ( [id] => 2709 ) Array ( [id] => 7048 )
Your echoing out each product rather than the list of products, so put the echo outside of the loop.
You are also never changing $i, so it will always write to the first element of the array, you can just use [] to add an item to the end of an array...
$meuproduto = array();
foreach($items as $itemId => $item) {
$meuproduto[] = $item->getProductId();
}
echo implode(", ", $meuproduto);
You Can Use Folowing code
$meuproduto = array();
foreach($items as $itemId => $item) {
$id = $item->getProductId();
array_push($meuproduto,$id);
}
print_r($meuproduto);

PHP for each loop returns only last element

I'm trying to save data from an array by using foreach but it's only saving the last element of the array every time.
Here is my code:
public function demo($cakeId, $percent) {
$query = $this->dbh->prepare("SELECT price, price * $percent / 100 as dprice FROM prices WHERE cake_id = ? ");
$query->execute(array($cakeId));
$prices = $query->fetchAll(\PDO::FETCH_ASSOC);
foreach ($prices as $key => $value) {
$d_amount = $value['dprice'];
$price = $value['price'];
$final_price = $price - $d_amount;
}
$query2 = $this->dbh->prepare("UPDATE prices SET discount_price = ? WHERE cake_id = ?");
$query2->execute(array($final_price,$cakeId));
$return['data'] = [];
$return['message'] = "Discount Added";
$return['msgType'] = true;
return $return;
}
$prices is an array containing all the prices but when I use $prices in a loop it only returns the last element.
Please help me on solving this.
What I can see from your code
It is not the issue or error of PHP or Mysql. Its issue of your logic
i.e.:
foreach ($prices as $key => $value) {
$xx = $value;
$query2 = $this->dbh->prepare("UPDATE prices SET discount_price = ?");
$query2->execute(array( $xx));
}
The update statment execute each and every time and replace all price of table. So you are getting last updated value which replace all previous update statements
$xxis created before any iteration and set to null. During each iteration if will be overwritten. It will not be destroyed at any time before leaving the scope of your script, function, method, ...
$xx;
foreach ($prices as $key => $value) {
$xx = $value;
$query2 = $this->dbh->prepare("UPDATE prices SET discount_price = ?");
$query2->execute(array( $xx));
}
For php variable declare inside loop you have to check this Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration? for your issue.
Also another thing you should check your array is not empty before loop :
And you have to add condition for your update query check some good stuff for mysql :
$xx;
if(!empty($prices)){
foreach ($prices as $key => $value) {
$xx = $value;
$query2 = $this->dbh->prepare("UPDATE prices SET discount_price = ?");
$query2->execute(array( $xx));
}
}
I Guess You Can do is That use $key
$key is a Indexing of Array Values in $prices Array
foreach ($prices as $key => $value) {
$query2 = $this->dbh->prepare("UPDATE prices SET discount_price = ?");
$query2->execute(array($value[$key]));
}
Hope This Helps.

Insert key value - array in array

I am getting some values (domain names) from a _POST which I have to insert into an "Array in an Array". The array is called $postValues["domainrenewals"] and the I need to create another array inside this one in the format:
domainname => 1 (where 1 is the number of years).n
My code:
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"] = array($value => "1");
}
var_dump ($postData);
The var_dump shows that only the last $key -> $value pair is being inserted into $postValues["domainrenewals"]
Any help, much appreciated.
In each pass of the foreach loop you're redefining $postValues["domainrenewals"] so of course only the last one is saved... Try doing this:
$postValues["domainrenewals"] = array();
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"][$value] = "1";
}
If you need to add another value to the array I'm assuming it's information of the domain, so you would do something like:
$postValues["domainrenewals"][$value]['your_first_value'] = "1";
// Then for your other value
$postValues["domainrenewals"][$value]['renewalpriceoverride'] = 285.00;
Try This:
$postValues = array();
$arr=array();
foreach ($_POST['renewthesedomains'] as $value) {
$arr["domainrenewals"]=$value;
$arr["no_of_years"]=1;
$postValues[] = $arr;
$arr=array();
}

How to select specific part of an array when two arrays are returned?

In a while loop I have:
$row = mysql_fetch_array($result)
Held under $row are two arrays which when shown using print_r display the following:
Array
(
[4] => Post Content
[value] => Post Content
)
Array
(
[4] => Post Title
[value] => Post Title
)
How can I choose "Post Content" and "Post Title" from the array without it being repeated in the while loop?
The original version of this question confused the duplication with the problem. The issue is how to extract the second array [value] when they are both held under $row.
You can also make sure the values won't be insterted twice using mysql_fetch_assoc() or mysql_fetch_row().
Thus:
$row = mysql_fetch_assoc($result);
Array
(
['value'] => Post Content
)
Array
(
['value'] => Post Title
)
You want to make sure an array only has unique values? If that doesn't work with the arrays in an array, it's classic de-duping with a store of what you've already seen.
$dedupedValues = array()
foreach ($row as $items) {
if (! is_set($dedupedValues[$items['value']])) {
$dedupedValues[$items['value']] = true; // we have this value
echo "echo the title/value....";
}
}
Another alternative is to improve the SQL that gets the data to begin with to avoid duplicates in the first place (see: MySQL 'DISTINCT')
Pim Jager showed much better way of doing this, but if you insist on using mysql_fetch_array():
$i = 0;
$size = count($row);
if ($size > 0) {
while ($i < floor($size / 2)) {
..... = $row[$i];
$i += 1;
}
}
Edit:
After reading again, I'm not sure if I quite understand the question.
If you have nested arrays for example:
$row = array('data1' => array('orange', 'banana', 'apple'),
'data2' => array('carrot', 'collard', 'pea'));
And you want to access each array then:
$data1 = $row['data1'];
// = array('orange', 'banana', 'apple')
$data2 = $row['data2'];
// = array('carrot', 'collard', 'pea')
// OR
$orange = $row['data1'][0];
$banana = $row['data1'][1];
$apple = $row['data1'][2];
$carrot = $row['data2'][0];
// ... so on..
Taking that in account the loop looks like this:
$i = 0;
$size = count($row);
if ($size > 0) {
while ($i < floor($size / 2)) {
$something = $row['data1'][$i]; //Or $row[0][$i]; using your example
$something = $row['data2'][$i]; //Or $row[1][$i]; using your example
$i += 1;
}
}
But I really suggest using mysql_fetch_assoc() and foreach loop, like in Pims Jagers example
Final solution was found by slightly restructuring the original query as per Topbit's suggestion and the use of two while loops.
while($row_title = mysql_fetch_array($result_title)){
$row_body = mysql_fetch_array($result_body);
// code
}
Thank you to all those who suggested solutions.

Categories