user2630069
user2630069

Reputation: 13

How to add a </tr><tr> automatically after every 2 <td>

i am retrieving results from MySQL with PHP based on user search

i want to add a automatically after every 2 s in the result

<?php
include_once("config.php");
isset( $_REQUEST['name'] ) ? $name=$_REQUEST['name'] : $name='';
$name = mysql_real_escape_string( $name );
if (strlen($name) >= 4) {

     $sql = "select * from places where speciality like '%$name%'";

     $rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error
    $num = mysql_num_rows( $rs );

    if($num >= 1 ){     
        echo "<table id='result-table'><tr>";           
while($row = mysql_fetch_array( $rs )){

    echo "<td>row[cname]</td>"; //here i want to add </tr><tr> after 2 <td>s

 }

    }else{
        echo "no records found</table>";
    }
}
?>

Upvotes: 0

Views: 3013

Answers (3)

Spudley
Spudley

Reputation: 168755

I suggest not putting them into a table at all; instead simply put them into <div> elements, with float:left and width:50% styles.

If you must put them into a table, and you want to do it the way you asked, you can use PHP's modulo operator (%) to divide the current record number by 2 and get the remainder. If it's 1, then add the <tr> tag:

if(++$rowNum % 2) {print "</tr><tr>";}

Upvotes: 0

Bora
Bora

Reputation: 10717

Used $i = 1; if ($i % 2 == 0) and $i++;

<?php 
include_once ("config.php");
isset ($_REQUEST['name']) ? $name = $_REQUEST['name'] : $name = '';
$name = mysql_real_escape_string($name);
if (strlen($name) >= 4) {
  $sql = "select * from places where speciality like '%$name%'";
  $rs = mysql_query($sql) or die('Database Error: '.mysql_error $num = mysql_num_rows($rs);
  if ($num >= 1) {
    $i = 1;
    echo "<table id='result-table'><tr>";
    while ($row = mysql_fetch_array($rs)) {
      echo "<td>row[cname]</td>"; //here i want to add </tr><tr> after 2 <td>s
      if ($i % 2 == 0)
        echo "</tr><tr>";
      $i++;
    }
  }
  else {
    echo "no records found</table>";
  }
}
?>

Upvotes: 2

mdziekon
mdziekon

Reputation: 3627

echo "<table id='result-table'><tr>";
$currentCount = -1;
while($row = mysql_fetch_array($rs))
{
    echo "<td>row[cname]</td>";
    $currentCount = ($currentCount + 1) % 2;
    if($currentCount == 1)
    {
        echo '</tr><tr>';
    }
}

Upvotes: 2

Related Questions