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)
<< June, 2009 >>
SMTWTFS
123456
78910111213
14151617181920
21222324252627
282930
Search Blog

Recent Comments
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)
Re: Just What IS a 'Service Layer', Anyway? (by Isaac at 8/02 2:25 AM)
Re: PayPal IPN Coldfusion CFC (by Soyestudiambre at 7/25 6:12 PM)
Re: PHP vs COLDFUSION (by Tony Garcia at 7/17 11:24 AM)
Re: PHP vs COLDFUSION (by dougboude at 7/14 8:45 AM)
Re: PHP vs COLDFUSION (by Lola LB at 7/14 5:51 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
Subscription Options

You are not logged in, so your subscription status for this entry is unknown. You can login or register here.

Re: Create Dynamic WHERE Clauses in PHP
Try explode() it's quicker for non regex splitting. See notes at: http://us3.php.net/split
Posted by Nikola on May 27, 2009 at 11:47 AM

Re: Create Dynamic WHERE Clauses in PHP
Also, check out http://www.php.net/mysql_real_escape_string. In combination with sprintf you can use it like a cfqueryparam. In your example you do not need to use it, but when looping over GET/POST and inserting values provided by the user you should, lest you get a nasty case of SQL Injection. PHP does not escape special characters in queries. But, you might have already know this.
Posted by nikola on May 27, 2009 at 11:55 AM

Re: Create Dynamic WHERE Clauses in PHP
Thanks Nikola! I knew there must be a way to protect against SQL injection, but somehow I managed to NOT find the mysql_real_escape_string function! Instead, I had written a small function that uses str_replace to escape characters. I'll definitely use the native function in the future.
Posted by dougboude on May 27, 2009 at 12:37 PM

Name:   Required
Email:   Required your email address will not be publicly displayed.

Want to receive notifications when new comments are added? Login/Register for an account.

Time to take the Turing Test!!!

17 plus 0 equals
Type in the answer to the question you see above:

Your comment:

Sorry, no HTML allowed!