Display Data in two column in Datatable Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Display Data in two column in Datatable without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have managed to display data in one column table, but would like to have two column instead. Is there a way of doing it? Here’s the code I currently have. Although, it works, it prints in one long column and would like to break it into two columns.

As you can tell, I’m using jQuery Datatable.

<?php
include('config.php');
mysql_connect($host, $username, $password) or die(mysql_error()) ;
mysql_select_db('people') or die(mysql_error()) ;

$data = mysql_query("SELECT * FROM names ORDER BY RAND() LIMIT 20") or die(mysql_error());
?>
<html>
<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script src="datatables/dt/media/js/jquery.dataTables.js">
    </script>
    <style type="text/css">
      /* @import "datatables/dt/media/css/demo_table.css";

     .result_container{
       width: 553;
      } */
      </style>
    <script>
      $(document).ready(function(){
        $('#the_table').dataTable();
      });
    </script>

</head>

<body>

 <?php

    echo "<table id="the_table">
                     <thead>
                            <tr>
                                <th>Latest names</th>

                            </tr>

                      </thead>

                      <tbody> ";

        while($info = mysql_fetch_array( $data )){

           echo"<tr> <td>" . $info['name'] . "</td> 
                </tr>";                     

            }
            echo" </tbody> ";
      echo "</table> ";
?>
     </body>
</html>  

Any help will be appreciated very much.

Answer

echo "<table id="the_table">
      <thead>
         <tr>
      <th>Latest names</th>
    </tr>
      </thead>

      <tbody>

      <tr>"; 


while($info = mysql_fetch_array( $data )){


// if remainder is zero after 2 iterations (for 2 columns) and when $c > 0, end row and start a new row:  
if( ($c % 2) == 0 && $c != 0){
echo "</tr><tr>";
}


echo "<td>" . $info['name'] . "</td>";

$c++; 

} // while..


// in case you need to fill a last empty cell:
if ( ( $i % 2 ) != 0 ){

// str_repeat() will be handy when you want more than 2 columns
  echo str_repeat( "<td>&nbsp;</td>", ( 2 - ( $i % 2 ) ) );
}


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

?>

We are here to answer your question about Display Data in two column in Datatable - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji