PHP FOR & WHILE

0

I create an array where it has years (2012,2013 ..) and when wanting to remove the elements from the table it does not throw anything at me this is the code that I use

for($i=0;$i<count($array);$i++){
    $sql = "SELECT SUM('VENTAS') VENTAS FROM EDORESULTADO WHERE ANO='".$array[$i]."'";
    $resultado=mysqli_query($conexion,$sql);
    $array=array();
    $index=0;
    while($row=mysqli_fetch_assoc($resultado)){    
        echo '<td class="tg-s6z2">'.$row['VENTAS'].'</td>';

    }
}

and the most curious thing is that if I remove the array if it works

$sql = "SELECT SUM('VENTAS') VENTAS FROM EDORESULTADO WHERE ANO='2012'";
    
asked by ANDRES PALMA HERNANDEZ 22.09.2018 в 21:36
source

1 answer

1

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.

    
answered by 22.09.2018 в 22:11