Chris G
Chris G

Reputation: 780

Dynamic value count in dropdown

I am trying to create a dropdown select menu as followed:

I have a table of products and each have a stock column. Let's say a product has a stock of 54. I want the dropdown to start at option 1 all the way to option 54.

Right now I have this:

<?php
## Conection part 

$sql = "SELECT * FROM product";
$result = $conn->query($sql);

while ( $row = mysqli_fetch_assoc($result) ) {   ## 1 While loop 

?>
    <tr>
        <td><input type="checkbox" name="id[]" value="<?= $row['ProductID'] ?>" /></td> 
        <td><?php echo $row['ProductID']; ?></td>
        <td><?php echo utf8_encode($row['ProductName']); ?></td>
        <td><?php echo $row['SKU']; ?></td>
        <select>
          <option value="1">1</option>
        </select>
    </tr>
<?php  
  }
$conn->close();
echo "<br>";
?>

Anyone have any idea how to accomplish this?

Thanks guys!

Upvotes: 0

Views: 1539

Answers (2)

Sean
Sean

Reputation: 12433

This is done using a simple for() loop, where you change the max in for($i=min;$i<=max;$i++) to your max, ie. $row['stock'].

<select>
  <?php for($i=1;$i<=$row['stock'];$i++){ ?>
    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
  <?php } ?>
</select>

also, if you want to account for when $row['stock'] is 0, you could show an out of stock message -

<?php if($row['stock'] > 0){ ?>
<select>
  <?php for($i=1;$i<=$row['stock'];$i++){ ?>
    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
  <?php } ?>
</select>
<?php } else { ?>
out of stock
<?php } ?>

Upvotes: 1

ameenulla0007
ameenulla0007

Reputation: 2683

Use range to avoid a loop.

$stockValue=50;
echo "<select><option>".implode('</option><option>', range(1,$stockValue))."</option></select>";

Upvotes: 2

Related Questions