mardi 4 août 2015

PHP: Adding to array replaces previous value

What I'm trying to do:
Pull data from a database and insert it into an array

The code I'm using:

sql = "SELECT * FROM `products`, categories WHERE category = cat_ID AND pro_ID = " . $_GET['id'];
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $name = $row['pro_name'];
            $cartContents[$name] = array(
                "id" => $row['pro_ID'],
                "name" => $row['pro_name'],
                "price" => $row['price'],
                "quantity" => $_GET['q']
            );
        }

The problem:
This does indeed take the values from the database and insert them into the array, but it replaces everything dat was in the array before this.

What I've tried:
- Replacing array(...) with [...]
- Using the following code:

$cartContents[$name]["id"] = $row['pro_ID'];
$cartContents[$name]["name"] = $row['pro_name'];
$cartContents[$name]["price"] = $row['price'];
$cartContents[$name]["quantity"] = $_GET['q'];

Any help would be greatly appreciated, thank you!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire