maphaneuf
maphaneuf

Reputation: 77

WHERE statement conditional

I am not sure what to write, must be simple but can't figure it out. I have a sql request I want to do.

simple request:

SELECT name FROM #table WHERE id=$id AND  phone='$phone'

Let say I do not provide the $phone variable or is empty, can I remove all the AND phone='$phone' from the select statement. so it would be

SELECT name FROM #table WHERE id=$id

Upvotes: 0

Views: 52

Answers (4)

Ryan
Ryan

Reputation: 14649

Check to see if the the $phone variable is set first.

I'm also assuming here that your phone variable is supposed to be an integer.

if($phone AND isset($phone)) {
   $phone = intval($phone);
   if($phone) {
       // sql query with the phone variable
   } else {
       // sql query without the phone variable
   }
}

Upvotes: 0

SQLMason
SQLMason

Reputation: 3275

Why not this?

SELECT name FROM #table WHERE id=$id AND (phone='$phone' or '$phone' = '')

Are you troubleshooting performance due to an index on [phone]?

Upvotes: 1

A.O.
A.O.

Reputation: 3763

$query = "SELECT name FROM #table WHERE id=$id";

if(isset($phone)){
    $query .= " AND phone = '$phone'";
}

Upvotes: 0

Marc B
Marc B

Reputation: 360612

Presumably you're building this query, so just build it dynamically. The basic logic would be:

if ($phone == '') {
   $sql = "SELECT name ... WHERE id=$id"
} else {
   $sql = "SELECT name ... WHERE id=$id AND phone='$phone'";
}

Upvotes: 2

Related Questions