1

SQL IN OPERATOR


I use the IN operator because I work with arrays in my SQL statement.

For example:

$city[1] = "'Paris'";
$city[2] = "'London'";
$cityString= implode(", ", $city);

SELECT * FROM Customers
WHERE City IN ($cityString);

But in my code I use the value's of my GET or POST array. But when the array is empty there are no values, so my SQL statement won't work. How can I solve this without if statements and have a list of thousands of SQL statements.

6
  • 4
    what's wrong with an if statement exactly? :S Commented Mar 28, 2014 at 14:32
  • 2
    The SQL query makes no sense if there is no list of cities (at least one) to compare against. To simply avoid a fatal error, you might have a dummy, impossible city name (e.g., '12345'), that should return 0 records. Commented Mar 28, 2014 at 14:32
  • @Tularis: Because it's not the only array I want to use, and if I make an if statement for every array it would be complex Commented Mar 28, 2014 at 14:52
  • @Phil Perry: Instead of returning 0 records I would like all my records. Commented Mar 28, 2014 at 14:52
  • 1
    you could also turn it into a function, or place it in a loop which loops over all your records/arrays/whatever, dynamically adding them to your resulting query ? Skipping empty search-parameters entirely (and speeding up your query that way!) Commented Mar 28, 2014 at 15:14

1 Answer 1

3

You can check if the array is empty:

if(!empty($city)) {
    $query = "SELECT * FROM Customers WHERE City IN ($cityString)";
    $result = mysql_query($query);

} else {
    // .. do something else ?
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.