Y
Y
Yapryntsew2016-01-06 21:37:07
PHP
Yapryntsew, 2016-01-06 21:37:07

How to make an array a condition for sql selection?

There is an array of the form key1=value1, key2=value2, etc., how to make it a condition of the sql query? That is, bring it to the form key1='value1' and key2='value2' and so on. It will be very interesting to hear an explanation and / or get links with useful information. Thanks to.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrzej Wielski, 2016-01-06
@wielski

This is fundamentally wrong.
What if something superfluous sneaks into the array? I understand you generate it.
At the very least, use mysql query builders (ORM).
Well, if you want - here is an example (very bad, please do not use it):

$whereClause = [];
foreach($array as $key=>$value){
  $whereClause[] = "`{$key}` = '{$value}'";
}
$whereClause = implode(' AND ', $whereClause);

E
Egor Stakhovsky, 2016-01-06
@ySky

For associative arrays, there is a function array_keys that gets all the keys of an array. Then you can simply run through the foreach loop and "blind" the desired line. There is also an extract
function that extracts the keys of an array as variables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question