如何在每2个后自动添加一个

时间:2013-07-29 11:24:58

标签: php mysql

我正在使用基于用户搜索的PHP从MySQL检索结果

我想在结果

中每2秒后自动添加一个
<?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>";
    }
}
?>

3 个答案:

答案 0 :(得分: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>';
    }
}

答案 1 :(得分:2)

已使用$i = 1; if ($i % 2 == 0)$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>";
  }
}
?>

答案 2 :(得分:0)

我建议不要把它们放在桌子上;而是简单地将它们放入<div>个元素中,使用float:leftwidth:50%个样式。

如果您必须将它们放入表中,并且您希望按照您的要求进行操作,则可以使用PHP的模运算符(%)来划分当前记录号2并得到余数。如果为1,则添加<tr>标记:

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