Assuming I have the following array array("valor1", "valor2", "valor3", "valor4", "valor5")
and I need to get all items from a MySQL table whose column X has a value equal to one of these items, like to proceed?
Assuming I have the following array array("valor1", "valor2", "valor3", "valor4", "valor5")
and I need to get all items from a MySQL table whose column X has a value equal to one of these items, like to proceed?
Assemble your query like this:
$array = array(0 => "valor1",
1 => "valor2",
2 => "valor3",
3 => "valor4");
$query = "SELECT * FROM sua_tabela WHERE";
foreach ($array as $k => $v) {
$query .= " 'campo_x' = '" . $v . "' OR";
}
//Retiro o último OR
$query = substr($query, 0, strlen($query)-2);
//O resultado deve ser:
//SELECT * FROM sua_tabela WHERE 'campo_x' = 'valor1' OR 'campo_x' = 'valor2'...
Now just do your query:
$mysqli = new mysqli("host", "user", "senha", "db");
$mysqli->query($query);
You can assemble your query in two ways.
First Form
$query = "SELECT * FROM table WHERE col IN (";
foreach ($array as $key => $value)
$query .= "'" . $value . "', ";
$query = substr($query, 0, strlen($query)-2) . ")";
Second Form
$query = "SELECT * FROM table WHERE";
foreach ($array as $key => $value)
$query .= " col = '" . $value . "' OR";
$query = substr($query, 0, strlen($query)-3) . ")";
The difference between the two forms is in the form in which the condition is written. I consider the first form as best, because it makes the size of the condition smaller, more organized and more legible .
First Form: ... WHERE col IN ('valor 1', 'valor2', 'valor3')
Second Form: ... WHERE col = 'valor 1' OR col = 'valor2' OR col = 'valor3'