Home > Net >  How to dislpay all animals that are status = 1 in PHP
How to dislpay all animals that are status = 1 in PHP

Time:10-24

I'm making an adoption website for a project.

I'm trying to display all animals whose status = 1 but the animals whose status = 0 keeps appearing in the category.

Is something wrong with my code? suggestions and corrections are welcome.

Thank you!

function.php

function get_animals($cat_id='', $animal_id='')
{
   
    global $con;

    
    $query = "SELECT * FROM animals WHERE status= 1";

    
   
    
    if($cat_id!='')
    {
        $query = "SELECT * FROM animals WHERE category_name='$cat_id'";

        
    }
    

    if ($animal_id!='')
    {
        $query = "SELECT * FROM animals WHERE id=$animal_id";
    }

   
    return $result = mysqli_query($con,$query);
   
    

}

This is my animals.php file

<?php 
     $cat_id = '';
     if(isset($_GET['id']))
     {
         $cat_id = mysqli_real_escape_string($con,$_GET['id']);
     }
     $particular_animal = get_animals($cat_id);
     
?>
    
    <!-- End Navigation -->

        <!-- Product Grid -->
<div class="container mt-5 ">
    <div class="row">

        <?php

            if(mysqli_num_rows($particular_animal))
            {


                while($row = mysqli_fetch_assoc($particular_animal))
                {
                    ?>

                    
        <div class="col-md-4 product-grid">
            <div class="row">
            <div class="image border border-info bg-light">


                <a href="animal_details.php? a_id=<?php echo $row ['id'] ?>">
                    <img src="admin/image/<?php echo $row['img']?>" class="w-100" alt="">
                </a>
                    <h4 class="text-center mt-2 text-info font-weight-bold"><?php echo $row ['name']  ?></h4>
                    <p class="text-center mt-2"><?php echo $row ['gender']  ?></p>
            </div>
            </div>
        </div>
        
        <?php

                    
                }

            }
            else
            {
                echo "record not here";
            }

        ?>


       
    </div>
</div>

CodePudding user response:

You're overwriting your $query (the one with the status) when $cat_id or $animal_id is set. Instead, add to the WHERE clause of your first query:

$query = "SELECT * FROM animals WHERE status= 1";
if($cat_id != '') {
    $query .= " AND category_name='$cat_id'";
}
if ($animal_id != '') {
    $query .= " AND id=$animal_id";
}

CodePudding user response:

If your function gets a category id or an animal id, then your query is overriden and your status criteria is lost. This is a 1-command solution:

function get_animals($cat_id='', $animal_id='')
{
    return mysqli_query($con,"SELECT * FROM animals WHERE status= 1" .
                             ($cat_id ? " AND category_name = {$cat_id} " : "").
                             ($animal_id ? " AND animal_id = {$animal_id} " : ""));
}
  • Related