0

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>";
    }
}
?>
user2630069
  • 13
  • 1
  • 2
  • possible duplicate of [Insert tr after every third loop](http://stackoverflow.com/questions/9008522/insert-tr-after-every-third-loop) and many others – JJJ Jul 29 '13 at 11:29

3 Answers3

2
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>';
    }
}
mdziekon
  • 3,531
  • 3
  • 22
  • 32
2

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>";
  }
}
?>
Bora
  • 10,529
  • 5
  • 43
  • 73
0

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>";}
Spudley
  • 166,037
  • 39
  • 233
  • 307
  • @AdamTester: Surely no, this really isn't tablular. Or, well if it is, he's not asking for it to be laid out out like tablular data; it's just a list of matching names. He wants it in two columns, but that doesn't change the fact that it's basically just a single dimensional data set. – Spudley Jul 29 '13 at 11:37