user3417953
user3417953

Reputation: 123

How to show one image instead of four images

In Mysql database I have column name "product_id" and there is while statement code to check if row exist ...

If value of product_id exist, then it will show "note-icon.png" image, if not exit it will say "No" but the problem is that let say that in "product_id" has four product_id's SAME NUMBER and then result will SHOW FOUR images, my question is that how to write code to show ONE image instead of FOUR images!

            <?php 
            $sql = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
            $query = "SELECT * FROM notes WHERE product_id = $product_id";
            $results = mysqli_query($sql, $query);
            while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
           if(isset($row['$product_id'])) {
            echo "<p>No </p>";
            } else {
            echo '<img src="images/note-icon.png" width="16" height="16" />';
            } }
            ?>

Upvotes: 0

Views: 66

Answers (2)

vp_arth
vp_arth

Reputation: 14982

Select only one row:

MySQL:

SELECT * FROM notes WHERE product_id = ? LIMIT 1  

SQL:

SELECT FIRST 1 * FROM notes WHERE product_id = ?

If you want to get all notes but draw one image per product you can do this:

$product_ids = array();
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
  if(!isset($row['product_id'])) {
    echo "<p>No </p>";
  } else {
    if(!isset($product_ids[$row['product_id']])) {
      $product_ids[$row['product_id']] = 1;
      echo '<img src="images/note-icon.png" width="16" height="16" />';
    }
  } 
}

Some code annotations:
$product_id in your query allowed, only if you are cast it to int before
else use placeholders (prepared statements)

if(isset($row['$product_id']))

What's this? think should be:

if(!isset($row['product_id']))

also you forgot to check $results, that it is not false, before using..

Upvotes: 3

Andrzej Reduta
Andrzej Reduta

Reputation: 767

U can use grouping

SELECT * FROM notes WHERE product_id = ? GROUP BY product_id

Upvotes: 0

Related Questions