SQL query with PHP array [duplicate]

2

I have an array that will be variable, eg $ ref = array ('123', '654', '555').

I wanted to do a SQL query to bring information from these references, something like:

SELECT *
FROM tabela_itens
WHERE ref = (array do PHP)

How can I do this?

The simple query I make, without array, looks like this:

$query = ("
SELECT *
FROM tabela_itens
WHERE ref = '123'
");
$db -> setQuery($query);
$results = $db -> loadObjectList();
foreach($results as $row){
    echo '<div>'.$row->ref.'</div>';
};
    
asked by anonymous 02.05.2018 / 19:56

2 answers

10
// exemplo array do PHP
$ref = array('123', '654', '555');

$in = '(' . implode(',', $ref) .')';

$SQL = 'SELECT * FROM tabela_itens WHERE ref IN ' . $in; 
  • Implode creates a string from an array by dividing the values of the array with a comma (or any value you prefer).
  • The IN operator allows you to specify multiple values in a WHERE clause.

example - ideone

    
02.05.2018 / 20:17
0

You can use the array as follows (I assumed that the data needs to be enclosed in single quotation marks. If not, just use the implode as indicated in the other answers):

<?php

$parametros = array_map(function($element){
    return sprintf("'%s'", $element);
}, array(1,2,3));

$query = sprintf("
    SELECT *
    FROM tabela_itens
    WHERE ref in (%s)
", implode(',', $parametros));

final content of $ query:

    SELECT *
    FROM tabela_itens
    WHERE ref in ('1','2','3')

Remembering that user-entered data should not be trusted. This means that the use of the PDO library is extremely recommended, actually using functions that clean any data garbage.

    

02.05.2018 / 20:24