RE: [PHP] Dynamic Queries

From: Date: Mon, 27 Nov 2000 23:33:16 +0000
Subject: RE: [PHP] Dynamic Queries
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-27498@lists.php.net to get a copy of this message
With things like this, I usually do the following: I have a few variables setup: $query $from $where $orderby etc $query is the first part of the query ie. "select col1, col2 .... " $from is the tables to select from " from table1, table2 ... " $where is the where clause of the query. So in your case you would write: *********************** $where = "WHERE "; // Note the space $bFirst = false; // flag to indicate if we have added to where clause the first time if (isset($fname)) { $where .= "fname = '$fname'"; // We note that this is the first time we've set the where clause $bFirst = true; } if (isset($lname)) { // If it's not the first adding to where clause, then add to it using conditional if ($bFirst == true) { $where .= "AND lname = '$lname'"; } else // First time adding to where clause $where .= "lname = '$lname'"; $bFirst = true; } } You keep going like that. At the end you get: $sql = $query.$from.$where.$orderby; Remember to put a space at the end of each of the strings. ie. "Select col1, col2 "; "from table 1 "; > -----Original Message----- > From: Jamie Jackson [mailto:NOSPAMjacksonjNOSPAM@calib.com] > Sent: Tuesday, 28 November 2000 09:18 > To: php-general@lists.php.net > Subject: [PHP] Dynamic Queries > > > Hello, > > Newbie question. What's the best, most elegant way to write dynamic > queries? Keep in mind my background is in ColdFusion (and I'm using > PHP3 and MySQL). > > Obviously, this is NOT the way to do it, but it'll give you an idea of > what I'm up to: > > $str_sql = " > select * > from pers_list2 > WHERE > if (isset($fname)) { > fname = '$fname' > } > if (isset($fname) && isset($lname)) { > AND > } > if (isset($lname)) { > lname = '$lname' > } > order by lname > "; > > Thanks very much, > Jamie > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net > For additional commands, e-mail: php-general-help@lists.php.net > To contact the list administrators, e-mail: php-list-admin@lists.php.net >

« previous php.general (#27498) next »