How to loop with while using array

6

Hello, I would like to know if it is possible to loop using while so I need the values of the $newsmedias1 array to be placed in while in order to make the appearance of the items with the given IDS in the Array as long as they are equal to the ids of the table column id column. I'm currently looping using foreach .

The $news['valores'] contains numbers of the table news column values separated by commas example 256,458,300 etc. These values are the corresponding ids of the table average column of this form when applying these values apply them to the explode then loop.

Code using foreach

<?php

    // IDS da Tabela media coluna valores
        $newsmedias1 = trim($news['valores'], ', ' );

    // Aplica explode para separar os valores por virgula
        $newsmedias2 = explode("," , $newsmedias1); 

    // Filtra somente valores completos
        $mediaID = array_filter($newsmedias2);  

    foreach ($mediaID as $item) 
{
    $sql = $MySQLiconn->query("SELECT * FROM medias WHERE id = '$item'");
    $row = $sql->fetch_array()
    echo $nome;

}   
 ?>

The problem is that this mode is not very efficient because if I want to show 45 items I will have 45 queries and this is very heavy I would like to make use of while to perform a single query showing all the results of the same form of foreach use.

    
asked by anonymous 22.10.2015 / 15:41

2 answers

6

As said by @rray, you can do this using WHERE IN

So:

SELECT * FROM medias WHERE id IN(1,2,3,4,5,6,7,8,9)

Another possible way would be to use the implode function to join the elements of array and create the correct syntax for IN

sprintf("SELECT * FROM medias WHERE id IN(%s)", implode(', ', array(1,2,3,4));
    
22.10.2015 / 16:02
1

In the sql query you can pass the array ...

query("SELECT * FROM medias WHERE id in( "+ $mediaID +"); ,

ai is just the foreach strip

    
22.10.2015 / 16:17