0

I have the following code to push data into an array if a condition is true however the result is not what I was hoping for;

         <?php
$sql = "SELECT * FROM cart WHERE sess_id = '$sess_id'";
$result = mysqli_query($conn, $sql);   
$items= array();

if (mysqli_num_rows($result) > 0) {
    // output data of each row

   while($row = mysqli_fetch_assoc($result)) 
{
    $items[] = [
        'sku' => $row["prod_sku"], 
        'quantity' => (int)$row["prod_qty"]
    ];
}
if ($postage === 4.00){
    array_push($items, "sku_GSxe2lDNfK5b6E", 1);
}
}
        $conn->close();
             ?>

I would like the second record to look the same as the first, excluding the record information. Can someone please tell me how do go about it. I have not done a lot with arrays and I cant find the information I need anywhere. Thanks in advannce.

[{"sku":"sku_GGBzZqwz44UhRf","quantity":1},"sku_GSxe2lDNfK5b6E",1]

I want it to output like this

[{"sku":"sku_GGBzZqwz44UhRf","quantity":1}, {"sku":"sku_GSxe2lDNfK5b6E","quantity":1},]

Edward68
  • 63
  • 1
  • 10

1 Answers1

1

Your existing code pushes two separate values into the array:

if ($postage === 4.00){
    array_push($items, "sku_GSxe2lDNfK5b6E", 1);
}

You want to push another array into the array:

if ($postage === 4.00){
    array_push($items, ["sku" => "sku_GSxe2lDNfK5b6E", "quantity" => 1]);
}

Also please note that your code is vulnerable to SQL injection attacks. You should use prepared statements with bound parameters, via either mysqli or PDO. This post has some good examples.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • Thank you. That worked well. I knew that I had to fix the SQL thing. I will do that when I upload the site to a live environment. – Edward68 Jan 02 '20 at 01:02
  • 1
    _"I will do that when I upload the site to a live environment."_ Do it *before* you upload to live. – Alex Howansky Jan 02 '20 at 01:07