php - Display posts in different columns -
this question has answer here:
below code gets blogs database , displays in single column on screen, want display blogs in multiple columns may three,with each column displaying 10 blogs ordered id, how that. if long answer here maybe mentioning method easy use can me.
this how call posts db:
$query = ("select blogs_id, title, body, posted_by, category blogs inner join categories on categories.category_id=blogs.category_id order blogs_id desc limit 10"); foreach($db->query($query)as $row){ $blogs_id = $row['blogs_id']; $title = $row['title']; $body = $row['body']; $posted_by = $row['posted_by']; } echo "<h2>$title</h2> <p>$body</p>";
using code below quite easy change number of columns time want.
<tr> <?php { //horizontal looper?> <td><div><?php echo $row['title']; ?></div> <div><?php echo $row['body']; ?></div> <div style="height:20px;"></div></td> <?php $row = $query->fetch(pdo::fetch_assoc); if (!isset($nested_list)) { $nested_list= 1; } if (isset($row) && is_array($row) && $nested_list++%3==0) { echo "</tr><tr>"; } } while ($row); //end horizontal looper ?>
this give 3 columns.
notice table row starts outside of loop. line echo "</tr><tr>";
ends table row , starts new 1 each time number of desired columns has been reached. in above code it's 3.
to change number of columns change $nested_list++%3==0
$nested_list++%5==0
, have 5 columns.
happy coding !
edit
place similar @ top of page above <doctype><html><head>
all should similar this...
<?php $host = 'localhost'; $db = 'database_name'; $user = 'database_user'; $pw = 'database_password'; $conn = new pdo('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "select blogs_id, title, body, posted_by, category blogs inner join categories on categories.category_id=blogs.category_id order blogs_id desc limit 10"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(pdo::fetch_assoc); $totalrows = $query->rowcount(); ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>untitled document</title> </head> <body> <table cellpadding="5" cellspacing="0" border="0"> <tr> <?php { //horizontal looper?> <td><div><?php echo $row['title']; ?></div> <div><?php echo $row['body']; ?></div> <div style="height:20px;"></div></td> <?php $row = $query->fetch(pdo::fetch_assoc); if (!isset($nested_list)) { $nested_list= 1; } if (isset($row) && is_array($row) && $nested_list++%3==0) { echo "</tr><tr>"; } } while ($row); //end horizontal looper ?> </table> </body> </html>
of course can "include" or "require" connection file in usual manner , change $conn
match code if necessary.
Comments
Post a Comment