Skip to content
Advertisement

prevent the link to open if it contain this condition

Sorry for this question I think it’s not difficult but I’m new to PHP, I tried to show some images of products with the link, If the item is available $row[‘p_status’]==’1′ ok the link will be opened else it display an alert, but I tried to write some code inside while loop but when I test it, it display many alert according the number of those items which is $row[‘p_status’]==’0′ if I have 5 products which it it’s not available if I click on an product it show me five alert.

Please help me this is my code.

<?php 
    $query = "SELECT * FROM products";
    $result = mysqli_query($conn,$query);                   
    while ($row = mysqli_fetch_assoc($result)) {
 ?>
    <div class="column">
            <img src="<?=get_image($row['image']);?>">
             <span>Add to Your Cart </span>
            <a href="mycart.php?add=<?=$row['product_id'];?>" id="a">
            <?php
            if ($row['pro_status']=='0') {
                # the link above not open but, how to do with code?
            }
            ?>
    </div>
<?php 
}
 ?>

Advertisement

Answer

You need an if statement to check if the status is 1. In case it’s 1 you show the link with href otherwise you call the onclick event to display the out of stock alert.

This is one of the solutions (easier for beginners):

<?php 
    $query = "SELECT * FROM products";
    $result = mysqli_query($conn,$query);                   
    while ($row = mysqli_fetch_assoc($result)) {
 ?>
    <div class="column">
            <img src="<?=get_image($row['image']);?>">
            <?php if($row['pro_status'] == 1) { ?>
            <a href="mycart.php?add=<?=$row['product_id'];?>">
              Add to Your Cart 
            </a>
            <?php } else { ?>
            <button onclick="return alert('Out of stock!')">Add to cart</a>
            <?php } ?>
    </div>
<?php 
}
 ?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement