I am trying to deduce information about several apartments from the database with the following query, it is certainly long, but (it seems to me, special attention should be paid to the IN condition):

$stmt = $pdo->prepare("SELECT flats.*, sort.value as sort, street.name as street, district.name as district, type.name as type, underground.name as underground, `line`.name as `line` FROM flats join sort on flats.sort=sort.id_sort join district on flats.district=district.id_district join street on street.id_street=flats.street join underground on underground.id_underground= flats.underground join type on type.id_type=flats.type join `line` on `line`.id_line=underground.line where id in (:id)"); $stmt->execute(array('id' => $str)); 

Two or three numbers are written in $ str, I check in phpMyAdmin - that's right, it displays the required number of lines. And then I try to output it on the site itself and get an array that contains the following:

  Array ( [0] => Array ( [id] => 1 [sort] => Студия [district] => Чертаново Южное [street] => Варшавское шоссе [underground] => Динамо [jk] => [floorf] => 5 [numb] => 1 [floorh] => 17 [elevator] => 2 [type] => Панельный [rooms] => 2 [floor] => 1 [price] => 5000000.99 [size] => 50.00 [bathroom] => 1 [balcony] => 1 [img] => 1q.jpg [popular] => 1 [enabled] => 1 [created_at] => 2016-10-21 22:41:50 [updated_at] => [line] => Замоскворецкая линия ) ) 

As a result, contains information about only one apartment.

I deduce as follows: $ res = $ stmt-> fetchAll (); print_r ($ res);

What am I doing wrong, where does the second go?

  • 2
    cannot pass an array to IN. Only one value is bound to a parameter. I need something like id in(?,?,?) (number of questions equals the number of transmitted id) and execute(explode(',',$str)) - Mike
  • 2
    either prepare () once a sql request and execute () several times - Jean-Claude
  • And you checked generated SQL request after substitution of parameters? - teran
  • I pass the string "1,2" to the parameter. Just when I have it, how can 2 parameters be passed, or maybe 3, if to write? - DumbSailor

1 answer 1

From the documentation

You cannot bind multiple values ​​to a single parameter; for example, you cannot bind two values ​​to a named parameter in an IN () expression.

You can not bind more values ​​than stated in the request; If the input_parameters array contains more elements than the PDO :: prepare () method declared in the SQL query, the query will fail and an error will be generated.

Here is the code to solve your problem.

 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); $values = [1, 2, 3]; $params = implode(',', array_fill(0, count($params), '?')); $stmt = $pdo->prepare("SELECT ... id IN ($params)"); if (!$stmt) { $err = $pdo->errorInfo(); die($err[2]); } if (!$stmt->execute($values)) $err = $stmt->errorInfo(); die($err[2]); }