0

Good day!

Iam making a query wherein the parameters will be stored in the ARRAY. My code is as follows:

    $conditions = array();
    if ($event != ''){
        $conditions[] = "event LIKE '%$event%'";   //ERROR HERE?
    }
    if ($event_name != 'Choose Category') {
        $conditions[] = 'event_name = "'.$event_name.'"';
    }
    if ($event_startDate != '') {
        $conditions[] = 'event_startDate = "'.$event_startDate.'"';
    }
    if ($event_endDate != '') {
        $conditions[] = 'event_endDate = "'.$event_endDate.'"';
    }

    $query = "SELECT *
          FROM eventlist 
          WHERE event_share = 1".implode(' AND ', $conditions); //IS THIS CORRECT?

    $result = mysql_query($query) or die('Error: Query failed');

There's already previous questions regarding this and i've already tried most of the answers there (I've tried so many combinations already). But still I cannot produce the results I desired. My first error is the LIKE.. Also, I am having error with my query statement. What I want is to combine all the parameters based on what user desired. If the user did not input any parameters, it will be catched by my IF statements.

Any suggestions will be highly appreciated. Thank you.

2 Answers 2

2

Your code above may generate somewhat query like as follows:

$query = "SELECT *
          FROM eventlist 
          WHERE event_share = 1  event like '%xyz%' "

that is you are missing AND before event...

suggestions:
1.) it would be better if you add some error code too
2.) use following code for $query:

$conditions[] = 'event_share = 1';
$query = "SELECT *
          FROM eventlist 
          WHERE ".implode(' AND ', $conditions);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Also Mr. KoolKabin.. :)
1

Try this:

 $query = "SELECT *
      FROM eventlist 
      WHERE event_share = 1 AND ".implode(' AND ', $conditions);

7 Comments

you might want to remove that last quote
if I put an AND there, if the user did not enter any parameter, then the "AND" is hanging..
There's a possibility that my four IF conditions will not be met.. so that AND will cause an error..
@newbie - then use $query = "SELECT * FROM eventlist WHERE event_share = 1 AND ".(($conditions!='')?implode(' AND ', $conditions):'');
@newbie you might want to try out KoolKabin's implementation too as it seems more elegant ;)
|

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.