-1

I have a php code to add a product to session, but it does not work as expected, below is my code:

<?php
session_start();
include 'db.php';
$status = 1;
if (isset($_POST['id']) && $_POST['id']!=""){
    $id = $_POST['id'];
    $sql = "SELECT * FROM website_tree WHERE id = '$id' ";
    $result = mysqli_query($link, $sql);
    $row = mysqli_fetch_array($result);
    $id = $row['id'];
    $name = $row['name'];
    $price = $row['price'];
    $image = $row['image'];

    $cartArray = array(
        'id'=>$id,
        'name'=>$name,
        'price'=>$price,
        'image'=>$image,
        'quantity'=>1
    );

    if(empty($_SESSION["shopping_cart"]['product'])) {
        $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray);
        $status = 1;
    }else{
        $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray);
        $status = 1;
    }
}
echo json_encode(array("status"=>$status)); 
?>

I get this warning: array_push() expects parameter 1 to be array, null

Can anyone help me to correct my code?

nico gawenda
  • 3,648
  • 3
  • 25
  • 38
  • Unrelated to question but you are open to SQL injections. Parameterize queries and use prepared statements. – user3783243 Aug 23 '20 at 12:04
  • 2
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 23 '20 at 13:22

2 Answers2

1

Define $_SESSION["shopping_cart"]['product'] if it is not defined (not set).

session_start();
include 'db.php';
$status = 1;
// here
if (!isset($_SESSION["shopping_cart"]['product'])) {
    $_SESSION["shopping_cart"]['product'] = [];
}

// more code here...


$cartArray = array(
    'id'=>$id,
    'name'=>$name,
    'price'=>$price,
    'image'=>$image,
    'quantity'=>1
);

// `array_push` works with array by reference
// so there's no need to reassign this variable
array_push($_SESSION["shopping_cart"]['product'], $cartArray);
$status = 1;
u_mulder
  • 54,101
  • 5
  • 48
  • 64
-2

Your code looks fine, but you need to put the session_start() right after <?php tag.

Be sure that there is NO output before this function (even a space symbol or so).

So change:

<?php
session_start();

to:

<?php session_start();
Ahmed Saleh
  • 126
  • 10