捂案勃朔爆尾冒垒烘起费蜗韭
记录指针是对记录进行操作,10-1是对字段进行遍历。
记录遍历指的是垂直方向的遍历,字段遍历指的是水平方向的遍历。
区别如图所示:
表结构:
新建:mysqli_record_result.php
使用记录指针遍历数据
代码:
<?php /** * 结果集中的记录指针与遍历操作 */ //连接数据库 require "mysqli_connect.php"; if($res=mysqli_query($db,'select * from staff')) { while($row=mysqli_fetch_assoc($res)) { print_r($row);echo "<hr>"; } } echo "<hr color='red'>"; mysqli_data_seek($res,0);//指针下移0 第一条数据 print_r(mysqli_fetch_assoc($res)); echo "<br>"; mysqli_data_seek($res,2);//指针下移2 第3条数据 print_r(mysqli_fetch_assoc($res)); //查看最后一条数据 echo "<br>"; mysqli_data_seek($res,mysqli_num_rows($res)-1);//记录数-1 最后一条数据 print_r(mysqli_fetch_assoc($res));
执行:
使用循环改写上方代码:
<?php /** * 结果集中的记录指针与遍历操作 */ //连接数据库 require "mysqli_connect.php"; if($res=mysqli_query($db,'select * from staff')) { while($row=mysqli_fetch_assoc($res)) { print_r($row);echo "<hr>"; } } echo "<hr color='red'>"; for($i=0;$i<mysqli_num_rows($res);$i++) { echo "<br>"; mysqli_data_seek($res,$i);//指针下移2 第3条数据 print_r(mysqli_fetch_assoc($res)); }
执行:
可以看到for循环结合记录指针遍历数据和使用while循环结果一模一样
使用这种方式的好处是:对于数据的控制更加灵活,比如可以输出奇数行数据
输出奇数行数据
<?php /** * 结果集中的记录指针与遍历操作 */ //连接数据库 require "mysqli_connect.php"; if($res=mysqli_query($db,'select * from staff')) { while($row=mysqli_fetch_assoc($res)) { print_r($row);echo "<hr>"; } } echo "<hr color='red'>"; for($i=0;$i<mysqli_num_rows($res);($i+=+2)) { echo "<br>"; mysqli_data_seek($res,$i);//指针下移2 第3条数据 print_r(mysqli_fetch_assoc($res)); }
执行:
邢淮酵情骑串佰财鳞书俄刷粉