简体   繁体   中英

Loop as column instead of rows dynamically based on total count

I know this involves a loop. I've done a number of searches but can't quite figure it out.

I'm using the following code to output the data with 3 items per row. What I'd really like to figure out how to do is to have them go ascending by column instead of by row, but dynamically depending on the number of records in the query, instead of defining the number of rows in the column.

<?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT lvm.luchtvaartmaatschappij, COUNT(*) AS CountLVMPhotos
    FROM tbl_photos p 

    LEFT JOIN tbl_luchtvaartmaatschappij lvm
    ON p.img_lvm = lvm.IATACode

    WHERE p.img_creator IN ('Daniël E. Cronk','Daniel E. Cronk')

    GROUP BY lvm.luchtvaartmaatschappij
    ORDER BY lvm.luchtvaartmaatschappij ASC ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "
<table id='fotosBij' class='tablesorter-dropbox table-responsive ui-table-reflow'>";
echo "<tbody>";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {
$items_in_row = 3 ;
$index = 0 ;   

echo '<tr >';

while($row = mysqli_fetch_assoc($result)){ 
 $index++ ;

echo "<td width='250px' valign='top'>" . $row['luchtvaartmaatschappij'] . "</td>";
echo "<td width='50px' valign='top'>" . $row['CountLVMPhotos'] . "</td>";
echo "<td width='80px'>&nbsp;</td>";

if ($index%$items_in_row == 0){
echo "</tr>"; 

  }
    }
echo "</tbody>";
echo "</table>";
    }
    }

mysqli_close($mysqli);

?> 

If I understand what you want correctly, this will do it:

if($result) {
    $row1html = "<tr>";
    $row2html = "<tr>";
    while($row = mysqli_fetch_assoc($result)) {
      $row1html .= "<td width='250px' valign='top'>". 
                   $row['luchtvaartmaatschappij'] ."</td>";
      $row2html .= "<td width='50px' valign='top'>". 
                   $row['CountLVMPhotos'] . "</td>";    
    }

    $row1html = "</tr>";
    $row2html = "</tr>";
    echo $row1html . $row2html;
}

There might be more elegant ways but this should work.

If you have a lot of data, that table is gonna get pretty wide though, so hopefully you have a design for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM