Foreach within While

1

Capture in an array the values received via checked checkbox post, these checkboxes have the values equal to the field names of the table, I need to query with while and print the fields referring to array:

<?php
    $campos = '''.implode('', '', $_POST['check']).''';
    $sql = mysql_query("SELECT id,$campos FROM chamado where status = 1");
    while($busca=mysql_fetch_array($sql)){
?>

    <tr class="odd gradeX">
        <td width="2%"><?php echo $busca['id'];?></td>
        <?php
            foreach ($quantidade_item as $tags) {
                echo '<td width="2%">'.$busca[$tags].'</td>';
            }
        ?>
    </tr>

<?php
    }
?>
What happens is that when you run the code, if you check that only one checkbox has been checked, the listing appears normally, but if you check more than one checkbox, the list displays only the data in the first column, the other columns return me undefined index -

    
asked by anonymous 22.05.2015 / 03:48

1 answer

0

If I understand correctly what you want, you need to change this line:

foreach ($quantidade_item as $tags) {

I do not see in your code where the $quantidade_item variable comes from and semantically does not make much sense to me because I think you want to iterate the fields that come from $_POST with the data you got from BD, right?

In this case I suggest you change the code to:

foreach ($_POST as $tags) {

But putting $_POST is not good practice (put it just to clarify the example). Another thing you can change is '' '' in the query fields as you do not need to.

Final code:

<?php
    $_campos = $_POST['check'];
    $campos = implode(', ', $_campos);
    $sql = mysql_query("SELECT id,$campos FROM chamado where status = 1");
    while($busca=mysql_fetch_array($sql)){
?>
    <tr class="odd gradeX">
        <td width="2%"><?php echo $busca['id'];?></td>
        <?php
            foreach ($_campos as $tags) {
                echo '<td width="2%">'.$busca[$tags].'</td>';
            }
        ?>
    </tr>

<?php
    }
?>
    
29.05.2015 / 07:52