Sign Doug's SOTR Petition!

Sign Doug's petition to his boss and help send him to Scotch on the Rocks in 2012!
Recent Entries
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!
NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
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: Basic Ajax Select List Filter in PHP (by opineemia at 2/02 8:47 PM)
Re: PHP vs COLDFUSION (by dougboude at 1/24 9:47 AM)
Re: PHP vs COLDFUSION (by WhatTheHeck at 1/23 7:03 PM)
Re: Recursive Functions in ColdFusion (by Marty McGee at 1/22 1:01 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by Rama at 1/10 11:05 AM)
Re: PHP Export to Excel Snippet (by rasha at 1/10 1:55 AM)
Re: Fredrick "French" Fry (by Picky eater at 1/09 2:21 PM)
Re: Disappearing IE Popup Window During Save/Open Dialog (by Vivekanand at 1/06 12:51 AM)
Re: Just What IS a 'Service Layer', Anyway? (by Ashishkumar Haldar at 1/05 7:49 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by ranjit sachin at 12/20 6:22 AM)
Re: Recursive Functions in ColdFusion (by Jason at 12/15 12:13 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by kt at 12/08 3:47 AM)
Re: PayPal IPN Coldfusion CFC (by Guest at 11/28 6:11 PM)
Re: SQL Forward Engineering with Visio 2003 Professional (by freddy villamil at 11/09 2:49 PM)
Re: Finally Found a Use for CFTHREAD (by criclebrava at 11/09 1:23 PM)
Re: Finally Found a Use for CFTHREAD (by assisisowsfub at 11/07 10:37 PM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by dougboude at 10/10 10:48 AM)
Re: Using Google as your CF Mail Server (by hlharkins at 10/09 10:24 AM)
Re: IRRITATING CF QUERY ERROR AND SOLUTION (by Peter Boughton at 10/07 3:15 PM)
Re: My Thoughts on the Current Presidential Contenders (by dougboude at 9/23 12:21 PM)
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



20 May 2009
Basic Ajax Select List Filter in PHP

I am a ColdFusion guy, without a doubt. At my new job, however, I have inherited the maintenance and enhancement duties of a large PHP application as well. One of the enhancements I was asked to make was to produce a select list of names that could be filtered on the fly as the user typed into a text box. Being somewhat new to PHP and having had to figure out a good approach to creating this feature, I thought I'd share it in case it helps someone else.

Picture if you will, a select list filled with names and immediately below it a text box for filtering that list. Better yet, here's what mine looks like:

 select list with ajax name filter


As the user begins typing in the text box, the select list begins to be filtered, re-filtering as each letter is added or removed.

I'm using the Prototype javascript library to perform the ajax calls, and a PHP script I call "adminAjax.php" that listens for and responds to those ajax calls. First off then, the HTML and JS that sets up the user interface:

<div id="namelist" name="namelist" style="height:350px;width:200px;"></div>
<div>
 Last Name: <input type="text" id="fltName" name="fltName" size="25" />
</div>

<script>
 Event.observe(window, 'load', function() {
  Event.observe('fltName', 'keyup', function(e){filterByName(e);});
  filterByName('');//this initially populates the select list with ALL names...
 });
</script>

 

basically, I have one div that will hold the select list ("namelist"), and some js that, on page load, will bind the 'filterByName' function to the keyup event on the 'fltName' textbox. So, with every character entered or removed from that textbox, the current value will be passed to the filterByName function. Here's the filterByName function:

function filterByName(strname){
 var params = new Hash();
 params.set('namestring',strname);
 params.set('actionval','getSelect');
 new Ajax.Updater('namelist','adminAjax.php',{parameters:params,method:'get'});
}

 

Okay, now on to adminAjax.php.

I'm using this template exclusively for ajax responses, so what I did was to create a switch/case statement that routes to the appropriate function based on the incoming 'actionval' parameter. Important to note: in my case, I chose to create the entire select list on this end and then return the completed HTML. The Updater that made the Ajax call will then place the returned HTML into the target div for us. Here's the code:

<?
 //make sure we have a default value for the actionval parameter...
 if(!isset($_GET['actionval'])){$_GET['actionval']='none';}
 
 switch ($_GET['actionval']){
  case 'getSelect':
   $retval = getSelect();
   echo $retval;
   break;
  case 'some_other_action':
   $retval = bogusCall($_GET['someParam']);
   echo $retval;
   break;
 }

 //end of our switch router! Now for the functions that feed it...

 function getSelect(){
  include("settings.php");
  $Query = "SELECT userid,firstname,lastname from myTable ";
  $Query .= " where firstname <> '' and lastname <> '' ";
  
  //filtering on lastname/firstname...?
  if(isset($_GET['namestring']) && strlen($_GET['namestring'])>0){
   $aStr = split(",",$_GET['namestring']);
   $len = strlen(trim($aStr[0]));
   $flen = (count($aStr) > 1)?strlen(trim($aStr[1])):0;
   $Query .= "AND SUBSTR(lastname,1,".$len.") = '".trim($aStr[0])."' ";
   if($flen > 0){
    $Query .= "AND SUBSTR(firstname,1,".$flen.") = '".trim($aStr[1])."' ";
   }
  }
  $Query .= "order by lastname,firstname";

         $Result=mysql_db_query($DBName,$Query,$Link);

         if(mysql_numrows($Result) == 0){
          $strField = "<br><br>No Records Found. Please Change Filter Values and Try Again.";
         } else {//we have some records...let's build the select list HTML.
   $strField ='<select name="selUsers" id="selUsers" size="20" style="width:200px;" >';
   while($row = mysql_fetch_assoc($Result)){
    $strField .= '<option value=\''.$row['userid'].'\'>'.$row['lastname'].', '.$row['firstname'].'</option>';
   }
   $strField .='</select>';
         }
         mysql_close();
  return $strField;  
 }

That's it!

You may be thinking what I was originally thinking, something along the lines of "wouldn't it just be faster to have given the page a json representation of all the names, then used JS to filter it on the client side?" Well, the answer (at least in my case) is NOPE. I am working with about 3,000 names, and my first approach was to do it using the JSON data. This worked fine in Firefox, but IE...of course it ran painfully slow. Using the Ajax approach and just creating a new select list as the filter value changes works surprisingly fast in all browsers!

Hope this helps.

If you would like a good set of starter snippets, you can grab the zip file here.

 

 

Posted by dougboude at 2:02 PM | PRINT THIS POST! | Link | 2 comments