php mysql我需要一次读取一条记录直到结束

时间:2013-08-16 17:34:22

标签: php mysql

我已经读过几个帖子堆栈溢出,我写了这个小程序。但是,不要一次读取记录 读同样的记录...... 我哪里错了?

// ...................................... NUMBER OF RECORD
$result = mysqli_query($data->connessione,"SELECT COUNT(id) FROM tsynapse")  ;
if ( $result == false ) { printf ("<br/> mysqli : Error Reading FROM tsynapse; <br/>");  break ; }
echo "<br/> record totali <br/>" ;
$row = mysqli_fetch_array($result) ;
echo $row[0] . "<br/>";

// ...................................... COUNTER
$k=$row[0] ;

while ( $k-- )
{
    // ...................................... READ ONE RECORD AT TIME
    $result = mysqli_query($data->connessione,"SELECT * FROM tsynapse LIMIT 1")  ;
    if ( $result == false ) { printf ("<br/> mysqli : Error Reading FROM tsynapse; <br/>");  break ; }

      $row = mysqli_fetch_array($result);
      echo $row['id'] . " XXX " . $row['tag'] . " XXX " . $row['token'] . " XXX " . $row['rule']. " XXX " . $row['trans']  ;
      echo "<br>";
}

3 个答案:

答案 0 :(得分:2)

要指定要检索的记录,您需要指定要检索的记录的偏移量和数量。见this MySQL reference

while ($k--)
{
   $result = mysqli_query ($data->connessione, "SELECT * FROM tsynapse LIMIT {$k}, 1");
   // etc.
}

从您发布的代码中,您似乎想要从tsynapse检索所有数据。 这是一种简化代码的更好方法:

$result = mysqli_query ($data->connessione, "SELECT * FROM tsynapse ORDER BY id DESC"); // Since it seems that you want to retrieve from last record.
$total_record_count = mysqli_num_rows ($result);

while ($row = mysqli_fetch_assoc ($result))
{
   echo $row['id'] . " XXX " . $row['tag'] . " XXX " . $row['token'] . " XXX " . $row['rule']. " XXX " . $row['trans']  ;
}

答案 1 :(得分:1)

您为每次迭代执行查询。所以每次都得到相同的结果集,每次都选择第一行。

迭代之前只执行一次查询,然后逐个选择行。

答案 2 :(得分:1)

您需要在循环外执行请求并删除查询中的limit 1

// ...................................... NUMBER OF RECORD
$result = mysqli_query($data->connessione,"SELECT COUNT(id) FROM tsynapse")  ;
if ( $result == false ) { printf ("<br/> mysqli : Error Reading FROM tsynapse; <br/>");  break ; }
echo "<br/> record totali <br/>" ;
$row = mysqli_fetch_array($result) ;
echo $row[0] . "<br/>";

// ...................................... COUNTER
$k=$row[0] ;

// ...................................... READ ONE RECORD AT TIME
        $result = mysqli_query($data->connessione,"SELECT * FROM tsynapse")  ;
        if ( $result == false ) { printf ("<br/> mysqli : Error Reading FROM tsynapse; <br/>"); }

while ( $k-- )
{     
      $row = mysqli_fetch_array($result);
      if($row == null)
      {
          break;
      }
      echo $row['id'] . " XXX " . $row['tag'] . " XXX " . $row['token'] . " XXX " . $row['rule']. " XXX " . $row['trans']  ;
      echo "<br>";
    //}
}