M
M
misc12014-11-03 11:48:10
PHP
misc1, 2014-11-03 11:48:10

PDO/MySQLi and array in query?

good time of day). There is such an array in the $jsondecoded variable:

array (size=3)
  0 => string 'B' (length=1)
  1 => string 'C' (length=1)
  2 => string 'D' (length=1)

How can you write such SQL in PDO or MySQLi?:
SELECT * FROM news WHERE id = /* значения $jsondecoded... eg. (B || C || D) */

PS There is also json: ["B","C","D"]
PPS The size of array and json can change up or down, depending on what the user chooses (that is, it can be ["B"] and [" B","C","D","S"])

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Push Pull, 2014-11-03
@misc1

$ids = array('B','C','D'); // ваш  $jsondecoded массив
$marks = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT * FROM news WHERE id IN ($marks)");
foreach ($ids as $k => $id) {
    $stmt->bindValue(($k+1), $id);
}
$stmt->execute();

F
FanatPHP, 2014-11-03
@FanatPHP

  • PDO - phpfaq.ru/pdo#in
  • Mysqli is half a screen of text, so it's really sad without a wrapper.

But with a wrapper - just the bottom of the line
$data = $db->getAll("SELECT * FROM news WHERE id IN (?a)", $json);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question