jeudi 26 juillet 2018

(PHP) 'If ' statement only echos out one side, it changes to the 'else' and changes back to the 'if' based off of which product is added to the cart

I'm going to start by telling you my desired outcome for the code: I want to echo to screen a sale price (if the product is in the sale in the database table), and a usual price (if the product is not in the sale in the database table).

I have tried to create an if statement, which I will outline underneath.

First things first: I establish a variable for the product table to use later on in the if statement.

$sql = "SELECT * FROM products WHERE id = ''";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result); 

To preface this, I created an array from submitted form data:

$_SESSION['shoppingcart'][0] = array (

        'id' => filter_input(INPUT_GET, 'ID'),
        'price' => filter_input(INPUT_POST, 'hidden_price'),
        'list_price' => filter_input(INPUT_POST, 'hidden_list_price'),
        'quantity' => filter_input(INPUT_POST, 'quantity'),

         );

Then I create another array that singles out the id column in the $_SESSION['shoppingcart'] array.

$product_ids = array();
$product_ids = array_column($_SESSION['shoppingcart'], 'id');

So, now I want to loop through the $productids array with a foreach loop.

foreach ($_SESSION['shoppingcart'] as $key => $cartprod): ?>

Now comes the if statement that I have been struggling with:

(just to add, $row['sale] is the column that I have as either 'yes' - for in the sale - or 'no' - for not in the sale.)

      <?php if ($row['sale'] == "yes"){
          echo '<td>£'.$cartprod['list_price'].'</td>';
              }else{
                  echo '<td>£'.$cartprod['price'].'</td>';
       }?>

    <?php endforeach;?>
        <?php endif;?>

So if I add a product to the array that is in the sale, it works fine, I can add them and it will echo out the $cartprod['list_price'] all day long, and vice versa - I can add products that are not in the sale to the array and it will echo out the $cartprod['list_price'].

The trouble comes when I try to add a product to the array that is in the sale along with a product that is not in the sale. Its one or the other, I can't have a variety of sale and none-sale products in the array.

Can anyone tell me what I am doing wrong? Thank you if you read this far :).

Aucun commentaire:

Enregistrer un commentaire