I have list of values that I want to fetch from my database. So List is long I want to fetch list in two columns. How can I break it in 2 columns. Eg..
taking list of aphabets
A | B
C | D
E | F
G | H
I | J
K | L
IN this way. I used following approach...
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$i = 1;
$j = ceil($total_rows/2);
while ( $i <= $j ) {
$result = mysql_fetch_assoc($sql);
?>
<tr>
<? if($i%2 == 0) { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<? } elseif($i%2 != 0) { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<? } ?>
</tr>
<?php $i++; } ?>
Its giving me output in this way..
A | A
B | B
C | C
NOTE - I wish to do it using PHP not using any jquery or javascript.
I would suggest jQuery columnizer as a solution to your problem http://welcome.totheinter.net/columnizer-jquery-plugin/
It seems you are resetting your result every time you loop. Set the $results outside the while. The more accepted way to do this is:
while ($row = mysql_fetch_assoc($sql)){
}
Then test $i to see if it is divisible by 2 (meaning you have 2 columns and need to add the end of row and beginning of new row tags).
if($i%2 == 0){
echo '</tr><tr>';
}
try:
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$i = 0;
$total_rows = mysql_num_rows($sql);
while ( $result = mysql_fetch_assoc($sql) ) {
$i++;
?>
<? if($i&1 == 1) { ?>
<tr>
<td class="navigation"><?php echo $result["pid"]; ?></td>
<? } elseif($i&1 == 0) { ?>
<td class="navigation"><?php echo $result["pid"]; ?></td>
</tr>
<? }
if($i == $total_rows && $total_rows&1 == 1){ echo "</tr>"; } ?>
<?php } ?>
Edited: Bug fixes..
i think Colmn rows this will work:
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$iOne = 1;
$iTwo = floor($totalRows/2);
foreach($iOne=1,$iTwo=ceil($totalRows/2); $iTwo < $total_rows; $iOne++,$iTwo++){
?>
<tr>
<td class="navigation"><?php echo mysql_result($sql,$iOne,'pid') ?></td>
<td class="navigation"><?php echo mysql_result($sql,$iTwo,'pid') ?></td>
</tr>
<?php
}
?>
Finally I succeeded with code.
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$i = 1;
while ( $result = mysql_fetch_assoc($sql) ) { ?>
<?php if($i%2 == '1') { ?>
<tr>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<?php } elseif($i%2 == '0') { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
</tr>
<?php } ?>
<?php $i++; } ?>