Kishore Kishore - 5 months ago 37
PHP Question

php table grid layout

I wanted to fetch data inside PHP table in grid layout. So I made this code. I don't know what went wrong or if I am missing something. I wanted the table to have three columns but it shows the table in a single column. Any help will be appreciated.

Here is the code:

<title>PAGINATION FILTER</title>
<?php include 'conn.php';?>

$stmt=$con->prepare('SELECT author, book_name, language FROM bk_tst_fltr ORDER BY id LIMIT 8');
$stmt->bind_result($author, $book_name, $language);
<table border="1" cellpadding="10">
if($i % 3 == 0){
?><tr><td><?php echo $author,"\n</br>",$book_name,"\n</br>", $language ;?></td>



Your if($i % 3 == 0){ line is just making you only show every third result - or it would if you actually incremented the $i variable anywhere.

You probably want to use that logic to start a new row - but still output every row.

Try something like this:

<table border="1" cellpadding="10"><tr>
$i = 0;
    if ($i > 0 && ($i % 3 == 0)) { // every third row, but not the first time

At the very beginning, it starts a table and the first row - and then it outputs a new <td> cell from the foreach loop for every result that you find - and the <tr> is closed at the very end. That would result in all the results being side-by-side on a single row.

Then the final step is that before every third row ($i % 3 == 0) - but not the first time ($i > 0) we want to close the current row and start a new one: </tr><tr>.

There's a couple other minor issues that I fixed above as well:

  1. You didn't actually increment the $i variable in your original code
  2. You were starting a new <tr> for every result you output, but only closing one of them (at the very end, after the loop).
  3. You were using </br> for newlines - which is not valid HTML. You want either <br> or <br/> instead.