问题描述:

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

网友答案:

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'";
}
网友答案:

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]?

网友答案:
$query = "SELECT name FROM #table WHERE id=$id";

if(isset($phone)){
    $query .= " AND phone = '$phone'";
}
网友答案:

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
   }
}
相关阅读:
Top