Select database items that contain something similar to the contents of an array

Asked

Viewed 29 times

-1

Assuming I have the following array array("valor1", "valor2", "valor3", "valor4", "valor5") and I need to take all items from a Mysql table whose column X has value equal to one of these items, how to proceed?

2 answers

1

You can mount 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 lies in the form in which the condition is written. I consider the first way as best, by leaving the size of the condition smaller, more organized and more readable.

First Form: ... WHERE col IN ('valor 1', 'valor2', 'valor3')

Second form: ... WHERE col = 'valor 1' OR col = 'valor2' OR col = 'valor3'

0

Mount 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.