phpundefined-variable

Error of undefined variable in my php code


I am new to php and I am trying to get products name from my product table of database and storing that data into $product array. I am getting error

count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\moed\cart.php on line 57

$sqlprod = "SELECT pname FROM products limit 10";
$sqlprice = "SELECT price FROM products limit 10";
$result = $conn->query($sqlprod);
$result1 = $conn->query($sqlprice);

if ($result->num_rows And $result1->num_rows > 0) {
    $products = array();
    $amounts = array();
    while($row = mysql_fetch_assoc($sqlprod)){
        $products[] = $row; 
    }
    while($row1 = mysql_fetch_assoc($sqlprice)){
        // add each row returned into an array
        $products[] = $row1;
    }
} 

// I am getting error of undefined variable products at the for loop below 
if ( !isset($_SESSION["total"]) ) {
    $_SESSION["total"] = 0;
    for ($i=0; $i< count($products); $i++) {
        $_SESSION["qty"][$i] = 0;
        $_SESSION["amounts"][$i] = 0;
    }
}

Solution

  • Your code is totally messed up.

    There's no need for multiple queries, just do one query that fetches both columns. You can still save each column in a separate array if you want.

    When you're fetching, you need to use $result, not $sqlprod.

    Since you're using the mysqli extension, you need to use mysqli_fetch_assoc(), not mysql_fetch_assoc(). But since you're using the OO style, it would be better to use $result->fetch_assoc().

    You were putting the prices in $products, not $amounts.

    You don't need a loop to create an array with the same elements multiple times, you can use array_fill() for this.

    $sqlprod = "SELECT pname, price FROM products limit 10";
    $result = $conn->query($sqlprod);
    
    $products = array();
    $amounts = array();
    while($row = $result->fetch_assoc()){
        $products[] = $row['pname'];
        $amounts[] = $row['price'];
    }
    
    if ( !isset($_SESSION["total"]) ) {
        $_SESSION["total"] = 0;
        $_SESSION['qty'] = $_SESSION['amounts'] = array_fill(0, count($products), 0);
    }