while loop inside foreach loop in PHP
378
i want to make a table that on the first column consist of name from database and on the second column consist of value from an array. this is what i have
<table>
<tr>
<?php $arr=array(3,5,2,4,1);
$name= mysql_query("SELECT name FROM table")
foreach ($arr as $rs){
while($n=mysql_fetch_array($name)){ ?>
<td><?=$n['name']?></td>
<td><?=$rs?></td>
</tr>
<?php } } ?>
</table>
i need an output like
name_a 3
name_b 5
name_c 2
name_d 4
name_e 1
thank you in advance.
Answer
Solution:
You don't need that
foreach
loop. Simply usefunction inside
while()
loop to get each array element. So your code should be like this:Furthermore, your business logic work will work only if the number of the rows in the table equals to the number of elements in the array. And if it's not the case then you need to use
LIMIT
clause in your query.Sidenote: Don't use
mysql_*
functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Useor
instead. .