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...

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Jay-oh
  • 426
  • 2
  • 6
  • 28
  • 5
    your code is vulnerable to sql injection – Marcin Orlowski Apr 13 '17 at 13:43
  • you should really look into basic [injection security](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – phadaphunk Apr 13 '17 at 13:45
  • Injection is my second problem. Just want the code to work. And then ill worry about the security stuff :) – Jay-oh Apr 13 '17 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. – ivospijker Apr 13 '17 at 13:46
  • Using prepared statement is not just about security. It will save you headaches in the future. All it takes is a random quote in random data to waste a day not understating why things are randomly failing. – Jason K Apr 13 '17 at 13:51
  • 1
    _"Just want the code to work. And then ill worry about the security stuff"_ Don't build software like that. – Alex Howansky Apr 13 '17 at 13:54

1 Answers1

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."'";