Skip to content
Advertisement

PHP why doesn’t my filtering works as it should be

So, I have to do a web store, where a person can filter the products. I have added the button [pod 300€] and [vsi izdelki]. But now when I click on button [pod 300€] it shows the products which are under 300€ but as well it shows all the products underneath. How to fix that so when I click [pod 300€] it shows only the products under 300€.

<?php 
include "header.php";

$connect = mysqli_connect("localhost", "root", "", "registration");

if(isset($_POST["add_to_cart"]))
{
    if(isset($_SESSION["shopping_cart"]))
    {
        $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
        if(!in_array($_GET["id"], $item_array_id))
        {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'item_id'           =>  $_GET["id"],
                'item_name'         =>  $_POST["hidden_name"],
                'item_price'        =>  $_POST["hidden_price"],
                'item_quantity'     =>  $_POST["quantity"]
            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        }
        else
        {
            echo '<script>alert("Izdelek je že bil dodan")</script>';
        }
    }
    else
    {
        $item_array = array(
            'item_id'           =>  $_GET["id"],
            'item_name'         =>  $_POST["hidden_name"],
            'item_price'        =>  $_POST["hidden_price"],
            'item_quantity'     =>  $_POST["quantity"]
        );
        $_SESSION["shopping_cart"][0] = $item_array;
    }
}

if(isset($_GET["action"]))
{
    if($_GET["action"] == "delete")
    {
        foreach($_SESSION["shopping_cart"] as $keys => $values)
        {
            if($values["item_id"] == $_GET["id"])
            {
                unset($_SESSION["shopping_cart"][$keys]);
                echo '<script>alert("Izdelek odstranjen")</script>';
                echo '<script>window.location="kosarica.php"</script>';
            }
        }
    }
}

?>
<!DOCTYPE html>
<html>
    <head>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>
    <body>
        <br />
        <div class="container">
            <br />
            <br />
            <br />
            <br /><br />
            <?php
            $connect = mysqli_connect("localhost", "root", "", "registration");
            if(isset($_POST["manj300"])){
            $query =mysqli_query($connect, "SELECT * FROM tbl_product WHERE price<=300");   

            while($row=mysqli_fetch_array($query)){ 
            ?>
                <div class="col-md-4">
                <form method="post" action="produkti.php?action=add&id=<?php echo $row["id"]; ?>">
                    <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
                        <img src="slike/<?php echo $row["image"]; ?>" class="img-responsive" /><br />

                        <h4 class="text-info"><?php echo $row["name"]; ?></h4>

                        <h4 class="text-danger">€ <?php echo $row["price"]; ?></h4>
                        <input type="text" name="quantity" value="1" class="form-control" />

                        <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />

                        <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />

                        <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Dodaj v košarico" />

                    </div>
                </form>
            </div>
            <?php   
            }
            }
            ?>
            <?php
            $connect = mysqli_connect("localhost", "root", "", "registration");
            if(isset($_POST["vsi_izdelki"])){
            $query =mysqli_query($connect, "SELECT * FROM tbl_product");    

            while($row=mysqli_fetch_array($query)){ 
            ?>
                <div class="col-md-4">
                <form method="post" action="produkti.php?action=add&id=<?php echo $row["id"]; ?>">
                    <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
                        <img src="slike/<?php echo $row["image"]; ?>" class="img-responsive" /><br />

                        <h4 class="text-info"><?php echo $row["name"]; ?></h4>

                        <h4 class="text-danger">€ <?php echo $row["price"]; ?></h4>

                    </div>
                </form>
            </div>
            <?php   
            }
            }
            ?>
            <form method="post" action="produkti.php">

            <input type="submit" name="manj300" style="margin-top:5px;" class="btn btn-success" value="pod 300€" />
            <input type="submit" name="vsi_izdelki" style="margin-top:5px;" class="btn btn-success" value="vsi izdelki" />


            </form>


            <?php
                $query = "SELECT * FROM tbl_product ORDER BY id ASC";
                $result = mysqli_query($connect, $query);
                if(mysqli_num_rows($result) > 0)
                {
                    while($row = mysqli_fetch_array($result))
                    {
                ?>
            <div class="col-md-4">
                <form method="post" action="produkti.php?action=add&id=<?php echo $row["id"]; ?>">
                    <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
                        <img src="slike/<?php echo $row["image"]; ?>" class="img-responsive" /><br />

                        <h4 class="text-info"><?php echo $row["name"]; ?></h4>

                        <h4 class="text-danger">€ <?php echo $row["price"]; ?></h4>

                        <input type="text" name="quantity" value="1" class="form-control" />

                        <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />

                        <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />

                        <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Dodaj v košarico" />

                    </div>
                </form>
            </div>
            <?php
                    }
                }
            ?>
            <div style="clear:both"></div>
            <br />

        </div>
    </div>
    <br />
    </body>
</html>

<?php
   include "footer.php";
?>

the result now

Advertisement

Answer

The problem is that if you get a filter, you make a db-request with the correct filter, but then after, you’re still making the default db-request which fetches all products.

Instead of making multiple db-requests, just make one. You can change the query depending on what filter you get from the client.

Alternative #1 – Dynamically build the query

Something like this:

$whereConditions = [];
$where           = '';

if (isset($_POST["manj300"])) {
    // Add this filter
    $whereConditions[] = 'price<=300';   
}

// Here you can add more conditions, just like the above if-statement

if ($whereConditions) {
    // We have a condition, implode and add WHERE
    $where = 'WHERE ' . implode(' ', $whereConditions);   
}

// Now put the where conditions in your query
$query = "SELECT * FROM tbl_product {$where} ORDER BY id ASC";
$result = mysqli_query($connect, $query);

if(mysqli_num_rows($result) > 0)
{
    while($row = mysqli_fetch_array($result))
    {
        // Your current code
    }
}
?>

The upside with this is method is that you easily can add more conditions/filters in the same query.

The downside is that the code gets a bit harder to read.

Alternative #2 – Choose a predefined query

You could have multiple queries defined and choose which to use:

// This is the "get all" query
$query = "SELECT * FROM tbl_product ORDER BY id ASC";

if (isset($_POST["manj300"])) {
    // We have a filter, let's override the default query
    $query = "SELECT * FROM tbl_product price<=300 ORDER BY id ASC";
}

$result = mysqli_query($connect, $query);

if(mysqli_num_rows($result) > 0)
{
    while($row = mysqli_fetch_array($result))
    {
        // Your current code
    }
}
?>

The upside with this method is that it’s very clean and easy to read and follow.

The downside is that you can only have one filter enabled at the same time.

9 People found this is helpful
Advertisement