Jump to content

Accessing values from associative php array


coderscoven

Recommended Posts

I have a php MySQL script which fetches information from MySQL database and stores them in an array with the latter working fine.

Now the issue comes when i want to access those values outside of the foreach loop. When inside, it displays them all but on doing a dump outside, only the last value is displayed.

 

  $db  = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

 if(!empty($_GET['sales_receipt2'])){
 
   
    $sales_rec2 = $_GET['sales_receipt2'];
    $_SESSION['sales_receipt2'] = $sales_rec2;
    
}
        $fetch_onhold_list = mysqli_query($db,"select prod_code as prod_code,
                                                        sales_name as prod_name,
                                                        sales_qty as prod_qty,
                                                        sales_unit_cost as prod_unit_cost from sales_history where
                                            
                                            sales_code='".$_SESSION['sales_receipt2']."'");


    $data_array = array();
    
    while ($salesByCode = mysqli_fetch_assoc($fetch_onhold_list)) {    
        $data_array[]    =    $salesByCode;
    }    
 
    foreach($data_array as $kp=>$pn){
    
        $_SESSION['onhold_cart_items'] = array($data_array[$kp]["prod_code"]=>array('prod_name'=>$data_array[$kp]["prod_name"], 'prod_code'=>$data_array[$kp]["prod_code"], 'prod_qty'=>$data_array[$kp]["prod_qty"], 'prod_unit_cost'=>$data_array[$kp]["prod_unit_cost"]));
    
    }
    
    var_dump($_SESSION['onhold_cart_items']);

 

Link to comment
Share on other sites

You're properly adding to $data_array in that while loop, storing multiple values in the array, however you're not doing that with the onhold_cart_items - you're just reassigning the value over and over again.

 

It looks like what you're trying to do is add a new value to onhold_cart_items using the prod_code as the array key? The correct syntax is

// $target_array = array($key => $value); - bad
$target_array[$key] = $value; // good
But what if the product already existed in the cart? What do you want to do then?

 

And are you using $data_array anywhere else? Because right now it's being wasted: you could just as easily use the while loop to add to the cart, instead of making an array and then looping over it.

Link to comment
Share on other sites

Also, within the foreach() loop, if you continue that way, you shouldn't have to refer to the array you're looping through.

 

$pn["prod_name"] is the same thing as $data_array[$kp]["prod_name"], on each iteration through the loop. That's the point of the foreach: $kp and $pn change each time through the loop, for each element of $data_array.

 

As said, if the only thing you're doing is populating the $_SESSION, then just do that directly in the retrieval loop.

Link to comment
Share on other sites

Some additional comments:

 

1. This first line is unnecessary

    $sales_rec2 = $_GET['sales_receipt2'];
    $_SESSION['sales_receipt2'] = $sales_rec2;

Instead, just use this

    $_SESSION['sales_receipt2'] = $_GET['sales_receipt2'];
 
2. You are using that user supplied value directly in your query. This is a very bad security risk that opens you up to having your entire database compromised. You should be using prepared statements.
 
 
3. You are not using your foreach() efficiently. You are using this to execute the loop
foreach($data_array as $kp=>$pn){
 
Then, in the loop, you are referencing the values like this
$data_array[$kp]["prod_code"]
That's just making things more complicated. You can reference the values using the $pn variable in a much more logical manner
$pn["prod_code"]
Edited by Psycho
Link to comment
Share on other sites

Thanks for the response. Actually these are products which are put on hold while say the client forgot to buy another product.

So as he looks for the item he wants, I unset his session, store his cart info in database and deal with another client. So when he comes back, I retrieve his cart info from database and display them in order to add the new item.

Let me try your suggestions and will give a response.

Link to comment
Share on other sites

If you're putting the information on hold, why not just make a copy of what's in the session? You don't need to hit the database or anything - store the "cart" in a temporary place and reset the cart.

 

I don't get the whole receipt thing (you've not finished ringing them up yet) but basically

$_SESSION['onhold_sales_receipt'] = $_SESSION['sales_receipt'];
$_SESSION['sales_receipt'] = // reset to empty for next customer
(plus apparently some stuff with $_GET)

 

As long as you don't delete stuff from the database, the old "cart" data will still be around when the customer is ready: put the onhold_sales_receipt back into the session where it normally would be then delete the old value.

Link to comment
Share on other sites

Okay i finally got the stuff to work. Thanks @requinix, @sepodati and @psycho

 

@requinix; I actually didn't think of that. I will try it in the next edit and also employ prepared statements.

 

Here is the code;

 

 $db  = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
 if(!empty($_GET['sales_receipt2'])){
 
    $_SESSION['sales_receipt2'] = $_GET['sales_receipt2'];
   
    $fetch_onhold_list = mysqli_query($db,"select prod_code as prod_code,
                                                        sales_name as prod_name,
                                                        sales_qty as prod_qty,
                                                        sales_unit_cost as prod_unit_cost from sales_history where
                                            
                                            sales_code='".$_SESSION['sales_receipt2']."'");

    
    while ($salesByCode = mysqli_fetch_assoc($fetch_onhold_list)) {    
        
        $data_array[$salesByCode["prod_code"]] = $salesByCode;
        
        $_SESSION["onhold_cart_items"] = $data_array;
    }    
        var_dump($data_array);

 }

 

$_GET['sales_receipt2'] is just a string of numbers which is generated on clicking the page having this cart stuff. It acts like a receipt number.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.