I want to print out a simple list of names from a mysql database into an html page that is using Bootstrap 3 css.
But rather than have one column with a long list I want to divide up the list in three columns ( on a desktop).
The code below does what I want but is not responsive. If I shrink the page all the names overlap. How can I print out the list in a responsive page (with three colums for desktop and perhaps two for mobile).
Thanks.
<?php
$result = mysqli_query($db_conx,"SELECT count(*) FROM mydatabase"); //Count Records
$row = mysqli_fetch_row($result);
$x=0; //Create a counter to count records that have been echoed.
$num = $row[0];
$sum =($num)/3; //Divide the total number of records by 3
$sql = mysqli_query($db_conx, "SELECT * FROM mydatabase"); //Get records
while($row = mysqli_fetch_assoc($sql)){
$x++; //Add 1 to counter
echo $row['name']; //echo row
echo "</br>";
if ($x>$sum){ //If the number of records already echoed is more than a third of the total then create a new column.
echo "</div>";
echo "<div class=\"col-sm-4\">";
$x=0; //Reset counter
}
} //End while loop
echo "</div>";
?>
Just try like this code 100% working and tested:
<?Php
$connection = new mysqli('HOST_NAME', 'USER_NAME', 'PASSWORD', 'DATABASE_NAME');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT * FROM products";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
?>
...
<?php
$rows = $result->num_rows; // Find total rows returned by database
if($rows > 0) {
$cols = 3; // Define number of columns
$counter = 1; // Counter used to identify if we need to start or end a row
$nbsp = $cols - ($rows % $cols); // Calculate the number of blank columns
$container_class = 'container-fluid'; // Parent container class name
$row_class = 'row'; // Row class name
$col_class = 'col-sm-4'; // Column class name
echo '<div class="'.$container_class.'">'; // Container open
while ($item = $result->fetch_array()) {
if(($counter % $cols) == 1) { // Check if it's new row
echo '<div class="'.$row_class.'">'; // Start a new row
}
$img = "http://yourdomain.com/assets/".$item['image_name'];
echo '<div class="'.$col_class.'">'.$img.'<h5>'.$item['name'].'</h5></div>'; // Column with content
if(($counter % $cols) == 0) { // If it's last column in each row then counter remainder will be zero
echo '</div>'; // Close the row
}
$counter++; // Increase the counter
}
$result->free();
if($nbsp > 0) { // Adjustment to add unused column in last row if they exist
for ($i = 0; $i < $nbsp; $i++) {
echo '<div class="'.$col_class.'"> </div>';
}
echo '</div>'; // Close the row
}
echo '</div>'; // Close the container
}
?>