SQL query with PHP array

Asked

Viewed 1,722 times

1

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

I wanted to make an SQL query to bring the information of these references, something like:

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

How can I do that?

The simple query I do, without array, is 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>';
};
  • can use .....WHERE ref IN (value1, value2, ...);

2 answers

9


// 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 array values with a comma (or any value you prefer).
  • The operator IN allows you to specify various values in a WHERE clause.

example - ideone

0

You can use the array as follows (I considered that the data needs to be passed inside simple quotes. If not necessary, simply use 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 one should not trust the data entered by the user. Which means that the use of the PDO library is highly recommended, using in fact functions that clean up any data junk.

Browser other questions tagged

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