为什么我不能从mysql第二次使用PHP获取


Why can`t I fetch from mysql using PHP on the second time?

请参照以下代码:

<?php
  //error_reporting(E_ALL);
  //ini_set('display_errors', '1');
  // 1. Create a database connection
  $dbhost = "localhost";
  $dbuser = "name";
  $dbpass = "password";
  $dbname = "widget_corp";
  $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
  // Test if connection succeeded
  if(mysqli_connect_errno()) {
    die("Database connection failed: " . 
         mysqli_connect_error() . 
         " (" . mysqli_connect_errno() . ")"
    );
  }
?>
<?php
    // 2. Perform database query
    $query  = "SELECT * ";
    $query .= "FROM subjects ";
    $query .= "WHERE visible = 1 ";
    $query .= "ORDER BY position ASC";
    $result = mysqli_query($connection, $query);
    // Test if there was a query error
    if (!$result) {
        die("Database query failed.");
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
    <head>
        <title>Databases</title>
    </head>
    <body>
        <?php
            while($row = mysqli_fetch_row($result)) 
            {
                echo "<pre>";
                print_r($row);
                echo "</pre>";
                echo "<hr />";
            }
        ?>
        <?php
            while($row = mysqli_fetch_assoc($result)) 
            {
                echo "<pre>";
                print_r($row);
                echo "</pre>";
                echo "<hr />";
            }
        ?>
        <?php
          // 4. Release returned data
          mysqli_free_result($result);
        ?>
    </body>
</html>
<?php
  // 5. Close database connection
  mysqli_close($connection);
?>

我希望返回的数据以不同的格式打印两次。

但是,当我运行程序时,只打印mysqli_fetch_row(不打印mysqli_fetch_assoc)。

你能解释一下为什么吗?

第一个循环一直到结果集的末尾,因此没有什么需要获取的了。您需要使用mysqli_data_seek()在循环之间重置指针(游标在结果集中的位置)。

的例子:

        while($row = mysqli_fetch_row($result)) 
        {
            echo "<pre>";
            print_r($row);
            echo "</pre>";
            echo "<hr />";
        }
        mysqli_data_seek($result, 0); // this resets the cursor to the first row
        while($row = mysqli_fetch_assoc($result)) 
        {
            echo "<pre>";
            print_r($row);
            echo "</pre>";
            echo "<hr />";
        }

另外,请注意您不需要那么多<?php ... ?>块—您可以组合相邻的代码块。只要删除这些组合:

?>
<?php