BC Tech : Free Tutorials and More Advertisement
Main
Wednesday, 07 January 2009
 
 
Conditional Queries Print E-mail
Tutorials / FAQs - Database
Once you get the hang of executing MySQL queries from PHP you'll realize that it is something very powerful. The most common use of this is for performing searches based on user input. We all know that many searchable fields are optional. How do you deal with it when certain search criteria isn't available? I show you how here.

 

This is an example query from a PHP function that I built. It accepts user input, but not all of the fields are required. The isSet functions and the conditional logic at the bottom of the query show you how to selectively ignore or add certain conditions.

 

Conditional Query Construction
  1. <?php
  2.   // a query for notes
  3.     function getNotes($tNoteID, $debugMode, $orderBy, $noteTypeID) {
  4.     $tNoteID = ( isset($tNoteID) ? $tNoteID : 0 );
  5.     $noteTypeID = ( isset($noteTypeID) ? $noteTypeID : 0 );
  6.     $queryStr = "
  7.       SELECT
  8.         n.noteID
  9.         , n.noteTitle
  10.         , n.noteURL
  11.         , n.noteText
  12.         , n.createDate
  13.         , DATE_FORMAT(n.createDate, '%d-%b-%Y') as fmtCreateDate
  14.         , n.updateDate
  15.         , DATE_FORMAT(n.updateDate, '%d-%b-%Y') as fmtupdateDate
  16.         , n.noteTypeID
  17.         , nt.noteType
  18.       FROM
  19.         notes n
  20.         LEFT JOIN noteTypes nt ON n.noteTypeID = nt.noteTypeID
  21.       WHERE
  22.         0=0";
  23.     if ( $noteTypeID > 0)  {
  24.       $queryStr = $queryStr." AND n.noteTypeID = ".$noteTypeID;
  25.     }
  26.    
  27.     if ( $tNoteID > 0)  {
  28.       $queryStr = $queryStr." AND n.noteID = ".$tNoteID;
  29.     }
  30.    
  31.     $orderBy = ( strlen($orderBy) > 0 ? $orderBy : "nt.noteType, n.noteTitle desc");
  32.     $queryStr = $queryStr." ORDER BY ".$orderBy;
  33.    
  34.     if ( $debugMode ) {
  35.       echo "<br>qryDtl: ".$queryStr."<br>";
  36.     }
  37.     return mysql_query($queryStr);
  38.   }
  39. ?>

 

 
Google
 
Web benconley.net
 
Top! Top!