0

I have two drop down menu's and when you select a value the value is saved in a session and passed trough AJAX to update a div. I have this working.

The reason I save the value in a session is because I need the database query to be dynamically filled (constructed). At this moment I have the following code:

    <?php
        $q = $_GET['q'];
        $_SESSION['theme'] = $q;
        $i = $_SESSION['category'];

        $query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = '".$i."'";
        $result = mysqli_query($conn,$query);
        $row = mysqli_fetch_assoc($result);
        echo "
        <a href='http://example.nl/search/'>" . $row['c'] .  "</a>";
    ?>

This counts all items from $q which is the value of the first drop down menu.

And WHERE Subcategorie = '".$i."', $i is the value from the second drop down menu.

But, now the problem. If the second value is empty (I haven't selected an option from that drop down menu) the query still add's this part to the query, like:

$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = ''";.

This makes the count from the first drop down menu always show 0. Is there away to only add the WHERE Subcategorie = '".$i."' when the second drop down menu has a value?

I'm still kind of new to MySQL so please be nice...

6
  • 5
    your code is vulnerable to sql injection Commented Apr 13, 2017 at 13:43
  • you should really look into basic injection security Commented Apr 13, 2017 at 13:45
  • Injection is my second problem. Just want the code to work. And then ill worry about the security stuff :) Commented Apr 13, 2017 at 13:45
  • In addition to what is said above this comment: I see that you are using two languages: English and another (Subcategorie). Try to use only one language in your code; consistent code is more maintainable. Commented Apr 13, 2017 at 13:46
  • 1
    "Just want the code to work. And then ill worry about the security stuff" Don't build software like that. Commented Apr 13, 2017 at 13:54

1 Answer 1

1

Use a query without WHERE clause. Then check if $i is not null, empty or whitespace. If so, add WHERE clause to your query.

$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded";
if($i != "")
    $query = $query." WHERE Subcategorie = '".$i."'";
Sign up to request clarification or add additional context in comments.

1 Comment

I did. Thanks for the tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.