douliao7354 2015-07-03 00:12 采纳率: 0%
浏览 31
已采纳

MySQLi - 这个例子中data_seek有什么意义?

I am new to MySQLi and following some examples. I am unclear as to why the function data_seek() is being used here in the for loop. If I'm not mistaken, it returns true/ false depending on if there is data in the current row passed to it. I'm only confused because the code runs fine without it, so it appears. Here is the example:

<?php

require_once 'login.php';

$connection = new mysqli($db_hostname, $db_username, $db_password,   $db_database);

if($connection->connect_error) die("Connection error: " . $connection->connect_error);

$query = "SELECT * FROM classics";
$result = $connection->query($query);

if(!$result) die($connection->error);

$rows = $result->num_rows;

for($i =0; $i < $rows; ++$i)
{
    $result->data_seek($i);    ///////////////////Why is this here?
    $row = $result->fetch_array(MYSQLI_ASSOC);

    echo 'Author: '     .$row['author']   .'<br>';
    echo 'Title: '      .$row['title']    .'<br>';
    echo 'Category: '   .$row['category'] .'<br>';
    echo 'Year: '       .$row['year']     .'<br>';
    echo 'ISBN: '       .$row['isbn']     .'<br><br>';

}

$result->close();
$connection->close();

?>

  • 写回答

1条回答 默认 最新

  • dongtun1209 2015-07-03 00:24
    关注

    This generally seems to be a case of unnecessary coding.

    When you call fetch_array(), it returns the row but also automatically advances the row pointer to the next row. In this case, the data_seek is going to seek to the same row it is already on during the next iteration (as opposed to your example, it doesn't return true/false on if the row exists, but literally makes the next call to fetch_array return the row with the given number.)

    The most likely case where this might be useful is if you wish to iterate over the same result set again, or seek weirdly around the result set (unlikely), which isn't happening here.

    A more common version is to go:

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
      echo 'Author: '......;
    }
    

    This version is reasonably valid and will work, however, it will not work with buffered result sets. Using num_rows() correctly requires that the entire MySQL result set is cached into the client before iterating over it which is OK for small data sets but will use a lot of memory if you are working on very large data sets. On the flip side, buffering the results in the client lets it free up the server connection and resources so there are ups and downs to both.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!