If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > PHP > Using PHP to construct SQL

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-13-11, 17:03
lecsiy lecsiy is offline
Registered User
 
Join Date: May 2011
Posts: 4
Using PHP to construct SQL

Hey,

I'm sure this is an easy question.

If you want to produce SQL with php for a search query. So you have say 5 criteria which are all optional and may or may not be inputted by the user. You cannot guarantee any of them.

When it comes to making the SQL in php you can use :

So if they exist then you can use AND for the 4 last criteria.

But for the first criteria if you have that as a WHERE if that one is not selected then the SQL just is a list of AND's with no starting WHERE.

Am i being really stupid and is there an easy answer?

Thanks

Alex
Reply With Quote
  #2 (permalink)  
Old 12-13-11, 17:18
healdem healdem is offline
Jaded Developer
 
Join Date: Nov 2004
Location: out on a limb
Posts: 9,262
there is a sneaky trick to set up your where clause using a quirk of SQL
PHP Code:
$WhereClause " where 1=1";
if (
abooleancondition)
{  
$WhereClause .= " and anumericcolumn = ".$anumericvalue;
}
if (
anotherbooleancondition)
{  
$WhereClause .= " and astringcolumn = '".$astringcolumn."'";

by using where 1=1 means you alwasy have something in your where clause, but it doesn't affect row selection.
then add your if statements to build the fully formed (or not) where clause
__________________
I'd rather be riding my Versys or my Tiger 800 let alone the Norton
Reply With Quote
  #3 (permalink)  
Old 12-13-11, 17:35
lecsiy lecsiy is offline
Registered User
 
Join Date: May 2011
Posts: 4
Your a genius!

Thanks so much, worked a charm!
Reply With Quote
  #4 (permalink)  
Old 12-13-11, 18:58
healdem healdem is offline
Jaded Developer
 
Join Date: Nov 2004
Location: out on a limb
Posts: 9,262
Quote:
Originally Posted by lecsiy View Post
Your a genius!

Thanks so much, worked a charm!
not really
I'd love to claim credit for that dodge
I got that trick from Rudy (R937) on this site.
__________________
I'd rather be riding my Versys or my Tiger 800 let alone the Norton
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On