How to do MYSQL and PHP query using an array as pro condition WHERE

1

I am making a query in MYSQL that brings the emails that were sent. These emails are in the emails column, separated by commas, as in the emails table sent below.

emailsenviados
IDenvio|emails
1      |[email protected],[email protected],[email protected]
2      |[email protected]

Then I need to use these emails that I'm getting as an array to make another query that will bring the name of the people of those emails, which are in the users table

ID|  nome  |email
1 | João   |[email protected]
2 | Maria  |[email protected]
3 | José   |[email protected]

How can I make a single query or is it in 2 itself? At first what I thought was to make the first query and make an explode of the results to make a second query, but I caught.

My query is done like this:

$query=("SELECT id FROM emailsenviados WHERE IDenvio=1");
$db -> setQuery($query);
$incs = $db->loadResult();

and the second:

$query=("SELECT name FROM users WHERE >>AQUI SERIA A CONDIÇÃO PARA ENCONTRAR OS EMAILS<<");
$db -> setQuery($query);
$results = $db -> loadObjectList();
foreach($results as $row){
echo $nome.'<br/>';
}
    
asked by anonymous 16.07.2018 / 21:48

2 answers

3

Make your query as follows:

$query=("SELECT name FROM users WHERE email IN (".$array_emails.")");

Where the variable $array_emails should actually be a string with all commas separated by commas, for example:

  

'[email protected] ',' [email protected] ',' [email protected] '

    
16.07.2018 / 21:58
1

MySQL has a function of its own, FIND_IN_SET .

The FIND_IN_SET( string1, string2 ) returns true if the first value ( string1 ) is contained in a comma-separated list passed in string2

Applying to your case:

SELECT campos FROM tabela WHERE FIND_IN_SET( email, emails )

Manual:

  

link

It's worth noting that this is the best way out if the number of emails is listed. For situations where the list is "fixed", David Alves's solution to use a concatenation on the PHP side is good.

    
16.07.2018 / 23:35