G
G
glem13372018-04-18 16:54:14
PHP
glem1337, 2018-04-18 16:54:14

How to use a named and unnamed variable at the same time in PDO?

If I substitute variables in the query string, then everything naturally works, but from a security point of view, this is not correct:

//Так всё работает
$brand = implode(',',$brand);
$sql = "SELECT * FROM models WHERE category_id=$cat_id AND brand_id IN ($brand)";
$stmt = $pdo->prepare($sql);
$stmt->execute();

If I try to substitute a named and unnamed variable, then I immediately get errors:
//Так ошибки
$in  = str_repeat('?,', count($brand) - 1) . '?';
$sql = "SELECT * FROM models WHERE category_id= :cat_id AND brand_id IN ($in)";	
$stmt = $pdo->prepare($sql);
$stmt->execute(array('cat_id'=>$cat_id, $brand));

Moreover, if instead of :cat_id I set the variable directly, then it works, almost exactly what is needed, but still not that:
$in  = str_repeat('?,', count($brand) - 1) . '?';
$sql = "SELECT * FROM models WHERE category_id=$cat_id AND brand_id IN ($in)";
$stmt = $pdo->prepare($sql);
$stmt->execute($brand);

In general, I can not find a way to do both at the same time. Can you please tell me how this can be implemented?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question