Search code examples
phphtmlcsspdfdompdf

SQL Query echo loop in 2 html table colums


Is it possible to echo database data into 2 html table colums like a loop? I can't make it work. Or do I need a different approach?

I need this to echo like a loop into 2 columns <?php echo $row['data']; ?>

This is what I have:

HTML Table
Col 1    |    Col 2
1. aaaa
2. bbbb
3. cccc
4. dddd
5. eeee
6. ffff
7. gggg
8. hhhh
9. iiii
10. jjjj

This is what I want:

HTML Table
Col 1         |     Col 2
1. aaaa             6. ffff
2. bbbb             7. gggg
3. cccc             8. hhhh
4. dddd             9. iiii
5. eeee             10. jjjj

Solution

  • Here code is for creating dynamic column and data, that might any length,

    Splitting into 5 groups and make it as column value. Worked output is below

    <?php
     //$row=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
     $row=array('aaa','bbbb','cccc','ddddd','eeeee','ffff','gggg','hhhh','iiii','jjjjj','kkkk','llll','mmmm','nnnnn','ooooo');
    ?>
    <table style="width:50%">
    <?php
    echo'<tr>';
    $i=0;
    foreach ($row as $key => $value) {
        if(($key)%5==0)
        {
            $i++;
            echo'<th>Col'.$i.'</th>';
        }
        $a[$i][]=$value;        
    }
    echo'</tr>';
    $forcount=count($a);
    $innerforcount=count($a[1]);
    for ($j=0; $j <$innerforcount ; $j++) {
        echo'<tr>';
        for($i=1;$i<=$forcount;$i++)
            echo'<td>'.$a[$i][$j].'</td>';
        echo"</tr>";
    }
    ?>
    </table>
    

    //Output

     Col1   Col2    Col3    Col4
    1   6   11  16
    2   7   12  17
    3   8   13  18
    4   9   14  19
    5   10  15  20
    

    //Sample out with text

     Col1   Col2    Col3
    aaa     ffff    kkkk
    bbbb    gggg    llll
    cccc    hhhh    mmmm
    ddddd   iiii    nnnnn
    eeeee   jjjjj   ooooo