Search code examples
phpmysqlsqlyog

I can't figure out how to function selected categories using $where in SQL


I want to show the selected query from the table

<?php 
    $where = "";

    if(isset($_GET['category']))
    {
        $catid = $_GET['category'];
        $where = " WHERE product.categoryid = $catid";
    }

Thus is the $where function to get the category

 $sql = "SELECT category.*,  
             category.category_id , items.id AS itemID,items.asset_tag,items.name,
                  items.brand,items.status,
                  items.quantity,items.category_id,
                items.color,items.texture,items.photo,items.date,
             items.fetch_item FROM items  LEFT JOIN category ON 
                     category.category_id=items.category_id 
                  WHERE  items.status = 'Available' AND items.fetch_item = '0' $where";


         ?>

Solution

  • Looks like you did small mistake, because in your "default" query you have already WHERE statement, so in the if you should use AND or OR instead of WHERE again:

    $where = "";
    if(isset($_GET['category']))
    {
        $catid=$_GET['category'];
        $where = " AND product.categoryid = $catid";
    }
    

    additionally you could make your injection of additional WHERE condition a bit more elegant by using sprintf() function. Take a look on example:

    $additional_condition = 'AND active=1'
    $statement = 'SELECT * FROM users WHERE condition=1 %s';
    echo sprintf($statement, $additional_condition);
    
    // Output: SELECT * FROM users WHERE condition=1 AND active=1