Mysql, selecting multiple rows that match an array of identifiers

First of all:

SELECT `key`, `value` FROM settings
 WHERE `key` = :base_url
    OR `key` = :google_analytics
    OR `key` = :site_domain

Is this the right choice for multiple lines? Or is there a better way? Because it’s not really OR, but they are all ... So it just doesn’t sound right.

Question number 2:

This is my query that selects paginated users:

SELECT id, email, verified, level, name_surname, age, sex, profession, education, location, privacy, suspend FROM users LIMIT :start, :results

Sometimes I want to pass an array of users to return to this request, for example array(1,2,3,4,5).

Obviously, just adding WHERE $arraydoesn't work. So how would I do that?

Sometimes I don’t want to pass this array of identifiers, so how do I switch between a state when there is a list of identifiers and when not? Am I just creating php if else in a make statement? This seems obvious, but it's better to ask about best practices :)

+5
3

where OR. in, :

SELECT 'key', 'value' FROM settings
 WHERE 'key' in ( :base_url, :google_analytics, :site_domain);

, :

SELECT * FROM users where id in (1,2,3,4,5);

, , implode ',' .

php:

<?php
$users = array(1,2,3,4,5);
$usersStr = implode(',', $users); // returns 1,2,3,4,5
$sql = "SELECT * FROM users where id in ({$userStr})";
....
+34

1

, , all of them, OR, , , . " " ", .

, , AND.

IN OR , .

2

` WHERE.. IN (..) ` - MySQL

, , :

$values = (array)$argument;
$conditions = implode(",", array_fill(0, count($values), "?");
// assuming you're using PDO
$stmt->execute($conditions);
0

1, , @Ronald ;

2, , :

public function myquery($condition){
    if is_string($condition){
         //do something to compose the query for string
    }

    if is_array($condition){
         //do something to compose the query for array
    }
}
0

All Articles