WHERE keyword to my query

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
salimali
Forum Newbie
Posts: 1
Joined: Mon Feb 10, 2014 12:29 am

WHERE keyword to my query

Post by salimali »

Hi,
I have a query like below

$query = "SELECT id,event_id,dayNo,themeName,sessionTime,sessionTopic from agenda WHERE event_id='4' AND dayNo='2'";

I don't want to use the same query for all requests.How can i add the WHERE keyword to my query only if the required parameters are passed to my service. I can change query at run time.

Thanks in advance
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: WHERE keyword to my query

Post by pbs »

you can write SQL query like this

Code: Select all

$sql_add = '';
if (isset($eventid))
    $sql_add = " AND event_id = '".$eventid."' ";
if (isset($dayno))
    $sql_add = " AND dayNo = '".$dayno."' ";
$query = "SELECT id,event_id,dayNo,themeName,sessionTime,sessionTopic from agenda WHERE 1 = 1 $sql_add";
may this will work for you
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: WHERE keyword to my query

Post by requinix »

I personally use an array and implode() like

Code: Select all

$conditions = array();
if (isset($eventid))
	$conditions[] = "event_id = {$eventid}";
if (isset($dayno)) {
	$conditions[] = "dayNo = {$dayno}";
$query = "SELECT id,event_id,dayNo,themeName,sessionTime,sessionTopic from agenda";
if ($conditions)
	$query .= " WHERE " . implode(" AND ", $conditions);
Post Reply