Question

I have yet another problem with my shopping cart. Everytime I run this code:

if(isset($_GET["atc"]))
{
    extract($_GET);
    $link = mysqli_connect("localhost", "root", "*******", "souljaz");
    $sql = "SELECT * FROM products WHERE id='{$pid}'";
    if($result = mysqli_query($link, $sql))
    {
        while($row = mysqli_fetch_assoc($result))
        {
            array_push($_SESSION["prod_names"], $row["name"]);
        }
    }
}

I get this error message:

Warning: array_push() expects parameter 1 to be array, null given in C:\Aapche2.2\htdocs\products.php on line 20

So I changed my code to this:

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

if(isset($_GET["atc"]))
{
    extract($_GET);
    $link = mysqli_connect("localhost", "root", "*******", "souljaz");
    $sql = "SELECT * FROM products WHERE id='{$pid}'";
    if($result = mysqli_query($link, $sql))
    {
        while($row = mysqli_fetch_assoc($result))
        {
            array_push($_SESSION["prod_names"], $row["name"]);
        }
    }
}

Then I get unexpected results because everytime the script runs the $_SESSION["prod_names"] = array(); is reset. So array_push() doesnt work as intented.

Was it helpful?

Solution

You could do a check on your array to see if it's empty before assigning it, that way it will only initialize the first time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top