NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< May, 2009 >>
SMTWTFS
12
3456789
10111213141516
17181920212223
24252627282930
31
Search Blog

Recent Comments
Re: Using Google as your CF Mail Server (by Mike at 9/07 4:02 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:34 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:33 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by Lola LB at 9/06 6:28 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by ComboFusion at 9/06 5:17 AM)
Re: Railo 3.1 on Windows Server 2008 and IIS7 - Part 3 of 3 (by Jon at 8/27 2:04 PM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Spacy at 8/24 3:46 PM)
Re: THE DAY CFUNITED DIED (by ComboFusion at 8/23 10:50 AM)
Re: My Grandpa (by Tasha at 8/10 4:29 PM)
Re: Just What IS a 'Service Layer', Anyway? (by dougboude at 8/02 10:10 AM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

21 May 2009
Create Dynamic WHERE Clauses in PHP

At times it is necessary to dynamically create delimited lists of items, such as in the WHERE clause of SQL queries. For instance, perhaps our query could have from one to N different OR statements in the WHERE clause based on selections a user makes on a search form, something like

"select userid, firstname, lastname from usertable

WHERE (rank >700 AND rank <1000) OR (rank >200 AND rank < 400) OR (lastname LIKE 'ar%') OR ...."

Looping over items and knowing when to insert a delimiter and when not to takes some extra coding, because you have to track if this is the first or last item in the list or array. Instead of worrying about tracking first or last items, what I do is simply insert the items I need to delimit into an array, and then dump them all out to a properly delimited statement by leveraging the 'implode' function.

Here's a snippet of code I use to create a dynamic WHERE clause for a sql query based on filter criteria submitted via a form. In this example, I am processing a submitted filter criteria named 'rankfilter' to build the WHERE clause for my query:

$Query = "SELECT userid,firstname,lastname,username,password FROM UserTable WHERE (";//start my query string...
$aRanks = split(",",$_GET['rankfilter']);//turn the submitted list of rank options into an array...
$aORs = array();//create an empty array to hold the individual criteria to be OR'd...
foreach($aRanks as $thisrank){
 switch($thisrank){
  case "core":
   array_push($aORs,'(rank >=700 AND rank <100000)');
   break;
  case "all":
   array_push($aORs,'(rank >=0 AND rank <100000)');
   break;
  case "1":
   array_push($aORs,'(rank >=500 AND rank <700)');
   break; 
  case "2":
   array_push($aORs,'(rank >=400 AND rank <500)');
   break; 
  case "3":
   array_push($aORs,'(rank >=300 AND rank <400)');
   break;
  case "4":
   array_push($aORs,'(rank >=0 AND rank <300)');
   break;   
 }
}

$Query .= implode(" OR ",$aORs); //transform the array of criteria into a properly delimited WHERE clause...

$Query .= ") ORDER BY lastname, firstname";

$Result=mysql_db_query($DBName,$Query,$Link);//execute the query

Don't focus so much on the switch/case statement as you do on the fact that every time I create a new OR statement, I'm pushing it onto my $aORs array. After I've created all of the needed ORs, I invoke the 'implode' function and spit out a nice WHERE clause where each statement is separated by " OR ".

Resulting SQL:

SELECT userid,firstname,lastname,username,password
FROM UserTable
WHERE ((rank >=700 AND rank <100000) OR (rank >=500 AND rank <700) OR (rank >=300 AND rank <400))
ORDER BY lastname, firstname


You can use this same approach any time you need to create some kind of delimited list of values. All you have to do is replace the first parameter in the 'implode' function with whatever you need the delimiter to be.

Hope this helps.

Posted by dougboude at 11:40 AM | PRINT THIS POST! | Link | 3 comments