Let's assume that this is your array (please verify that the variable names are correct);
$array=array(2012,2013,2014,2015);
You can extract the values of the array separated by a comma with implode
:
$sqlParams=implode(",",$array);
And modify the query, using IN
. That way you avoid sending a query for each item (which would affect performance). The code goes like this, without needing the old loop for
or foreach
:
$sql = "SELECT SUM('VENTAS') VENTAS FROM EDORESULTADO WHERE ANO IN($sqlParams)";
$resultado=mysqli_query($conexion,$sql);
while($row=mysqli_fetch_assoc($resultado)){
echo '<td class="tg-s6z2">'.$row['VENTAS'].'</td>';
}
If in your database the column ANO
is not numeric, you can create the parameters IN
surrounded by single quotes as follows:
$sqlParams = "'" . implode ( "', '", $array ) . "'";
Here the query would be like this:
SELECT
SUM('VENTAS') VENTAS
FROM EDORESULTADO
WHERE ANO IN('2012', '2013', '2014', '2015');
If, on the contrary, ANO
is of type INT
, you leave it as it is at the beginning. The query that will occur will look like this:
SELECT
SUM('VENTAS') VENTAS
FROM EDORESULTADO
WHERE ANO IN(2012, 2013, 2014, 2015);
Note on security: Your code can be highly vulnerable to SQL injection attacks. When you handle data that comes from
other sources, the use of prepared queries is convenient.