Philip Kirkbride
Philip Kirkbride

Reputation: 22879

Using PHP & MySQL to sort Events by multiple types.

I need to create a small piece of code to allow me to filter my events database based on category types users have selected.

I currently have it working for users who have only one category selected...

  $user_qstring = "SELECT types FROM tbl_users WHERE user_id='".$_SESSION['id']."'";
  $user_result = mysql_query($user_qstring);
  $user_row = mysql_fetch_array($user_result);

  $type_filter = $user_row['types'];
  if(isset($type_filter) && $type_filter !="") {
  $day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND     
  type='".$type_filter."'";
  }else{
  $day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."'";
  }

I need to alter this code so that if $type_filter is set and contains multiple categories in the following format.

Festivals,Sports,Education

And have the query automatically add...

OR type='".$type_filter[2]."' OR type='".$type_filter[3]."' OR ect...

I have been able to solve the problem using multiple...

elseif(){
}

Statements, but need a solution that is scalable to unlimited types.

I know I need to start by changing $type_filter to a list using explode...

$type_filter = explode(",", $user_row['types']);

But I'm still having trouble putting it all together for a short elegant solution.

Upvotes: 0

Views: 96

Answers (2)

roman
roman

Reputation: 11278

try something like the follwing sql

select * from ... where type in ('one', 'two', ...) ...

and as a remark - always escape get/post data using mysql_real_escape_string or you are vulnerable to injection attacks.

Upvotes: 0

Allain Lalonde
Allain Lalonde

Reputation: 93348

You will need to confirm that $type_filter does not contain single quotes first otherwise you're an easy target for sql injection attacks.

$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND type IN ('" . implode("','", explode(',', $type_filter)) . "')";

Upvotes: 1

Related Questions