Nicolaj Reck
Nicolaj Reck

Reputation: 41

If and else won't work

So, I guess this is pretty simple, but I can't really figure it out.

I'm trying to display a discount price, if it's set in the databse, and if not, display the regular price.

It displays the discount price if it's there, but it doesn't display the regular price, if it's not there?

if (isset($row['discount']))
      {
        echo $row['discount'];
      }

      else
      {
        echo $row['price'];
      }

Var dump

300 array(14) { [0]=> string(1) "1" ["id"]=> string(1) "1" [1]=> string(14) "Shoon slips UK" ["navn"]=> string(14) "Shoon slips UK" [2]=> string(17) "Importeret fra UK" ["tekst"]=> string(17) "Importeret fra UK" [3]=> string(3) "450" ["pris"]=> string(3) "450" [4]=> string(3) "300" ["tilbud"]=> string(3) "300" [5]=> string(59) "http://localhost/slipseknuden/assets/img/slips/slips1_2.jpg" ["billede"]=> string(59) "http://localhost/slipseknuden/assets/img/slips/slips1_2.jpg" [6]=> string(5) "Shoon" ["ka

The whole code

  $sql = "SELECT * FROM produkt ORDER BY RAND() LIMIT 2";
  $result = mysqli_query($db, $sql);

  while($row = mysqli_fetch_array($result)) {

?>

<div class="media">
  <div class="media-left media-middle">
    <a href="#">
      <img class="media-object sideobject" src="<? echo $row['billede']; ?>" alt="<? echo $row['navn']; ?>">
    </a>
  </div>
  <div class="media-body">

    <h3><? echo $row['navn']; ?></h3>
    <p><? echo $row['tekst']; ?>...</p>

    <?php

      if (isset($row['tilbud']))
      {
        echo $row['tilbud'];
      }
      else
      {
        echo $row['pris'];
      }

    ?>

Upvotes: 1

Views: 79

Answers (2)

Anto S
Anto S

Reputation: 2449

can you please try this.

<?php

  if (isset($row['tilbud']) && !empty($row['tilbud']))
  {
    echo $row['tilbud'];
  }
  else
  {
    echo $row['pris'];
  }

?>

I guess even though discount value is not there the variable will be still there.

Upvotes: 1

Muhammad Abdul-Rahim
Muhammad Abdul-Rahim

Reputation: 2010

Instead of using isset please try using array_key_exists instead. While some systems seem to allow isset for checking a key in an array, I learned the hard way a while back that some do not.

if( array_key_exists('discount',$row) )
    echo $row['discount'];
else
    echo $row['price'];

Upvotes: 1

Related Questions