Вопрос

I am trying to set a session on an array but if I navigate away from the page and come back to it I will get errors looks like my session is not keeping data.

Warning: Invalid argument supplied for foreach() in /home5/onlinepc/public_html/action/subs/custompcorder.php on line 75

Notice: Undefined index: quantity in /home5/onlinepc/public_html/action/subs/custompcorder.php on line 75 Warning: Invalid argument supplied for foreach() in /home5/onlinepc/public_html/action/subs/custompcorder.php on line 75 ....

 <?php
 session_start();
 ?>

 <?php

 foreach (array('part_id', 'quantity', 'price') as $pos) {
 foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
 }
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices =  $_POST['price'];

$_SESSION["cart_array"] = array();

$size = count($ids);

for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$_SESSION["cart_array"][] = array(
"part_id"     => $ids[$i], 
"quantity"    => $quantities[$i],
"price"       => $prices[$i]
);
}

if (!empty($_SESSION["cart_array"])) {
$values = array();
foreach($_SESSION["cart_array"] as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}',    '{$item['price']}','$orderid')";
}

$values = implode(", ", $values);

$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price,order_id) VALUES   {$values}    ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Number of item selected: ' . mysqli_affected_rows($con)."<br/>";


} else {

echo 'query failed: ' . mysqli_error($con);

  }

  }

 }

?>
Это было полезно?

Решение

I think your code is very similar to something im doing. From what I can see when you navigate back to the page you are starting a new session each time the page is loaded again. Try placing this underneath you starting of the session code.

if(!isset($_SESSION['cart_array'])){
$_SESSION['cart_array'] = array();
}

Другие советы

Just wrap your whole code in another conditional like this:

if (isset($_POST['part_id']) && isset($_POST['quantity]) && isset($_POST['price])) {
  foreach (array('part_id', 'quantity', 'price') as $pos) {
    // Your core code here.
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top