user1299028
user1299028

Reputation: 315

What character can i use in mysql query to represent all results?

Im trying to create a php script that queries a database based on filter input from users

So essentially i want

select * from table where parent_id = '$filter_value'

However i want to apply a default value to $filter_value which will take effect if the user doesnt specify any filters, and will pull up all possible results.

I tried using * but it didnt work...

Upvotes: 1

Views: 190

Answers (4)

PatomaS
PatomaS

Reputation: 1603

It's not exactly what you asked, but it is very close and I think a better way. You can do something like this:

if ( empty( $filter_value ) === false ) {
    select * from table where parent_id = '$filter_value'
} else {
    select * from table
}

That is just an example, not good php syntax.

But the idea is that if you want to have different behaviours depending on something, then you should program it that way, for instance, with an if, that way, you know what happens in each case and control the situation, not depending on what mysql does with the empty value passed.

Upvotes: 1

lc.
lc.

Reputation: 116498

Two ways:

  1. Compare the value to NULL

    SELECT * 
    FROM table
    WHERE ($filter_value IS NULL OR parent_id = '$filter_value')
    
  2. Dynamically create the SQL based on whether $filter_value contains a value. If it does not, your query should simply be:

    SELECT *
    FROM table
    

Upvotes: 3

Petah
Petah

Reputation: 46040

Check if the filter variable is null, or just wrap your query in an if statement:

SELECT * FROM baz WHERE foo = :bar OR :bar IS NULL

Upvotes: 2

user1299028
user1299028

Reputation: 315

Ok, i tried just inserting a blank space as the default var value, as in

$filter_value = ''

Solved the problem :$

Upvotes: 0

Related Questions