How to loop with while using array

Asked

Viewed 1,244 times

6

Ola would like to know if it is possible to make a loop using while as follows I need the array values $newsmedias1 be placed in the while in order to perform the appearance of items with the IDS determined in the Array provided that they are equal to the IDS of the table medias column id. I am currently performing the loop using the foreach.

To $news['valores'] contains table numbers news column values separated by comma example 256,458,300 etc these values are the corresponding ids of the table medias column id this way when applying these values apply them to explode then performs the loop.

Code with use of 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 being very efficient because if I want to show 45 items will hold 45 queries and this weighing very would like to make it work using while in order to perform a single query showing all the results in the same way as the use of foreach.

  • 1

    Tried a WHERE IN(?,? ... ?) ?

  • I don’t understand why WHERE IN does not apply in your case.

2 answers

6


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

Thus:

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

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

sprintf("SELECT * FROM medias WHERE id IN(%s)", implode(', ', array(1,2,3,4));
  • I gave an update on the question the problem and that I need $news['values'] to be applied in Where I had put numeric values separated by comma in $news['values'] to get more explanatory and when I tried to put the $news['values'] inside gave error. Fatal error: Call to a member function fetch_array() on a non-object

  • Thank you for your help and both your answers have been extremely helpful. Worked the first perfectly alternative what I had to do was just by a $newsmedias1 inside the IN because in the case other parameters are used to perform calculation to make text appear singular or plural.

1

In query sql you can pass the array ...

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

It’s only a foreach

Browser other questions tagged

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