【问题标题】:mysqli_fetch_row doesn't return results, but mysqli_fetch_assoc doesmysqli_fetch_row 不返回结果,但 mysqli_fetch_assoc 确实
【发布时间】:2015-03-27 00:15:53
【问题描述】:

我正在为作业编写一个简单的 php 页面,其中一个标准是同时使用 mysqli_fetch_assoc 和 mysqli_fetch_row。我对两者都使用相同的查询:

<?php
    // Perform database query
    $query = "SELECT * FROM player JOIN stat ON player.playerId = stat.playerId";
    $result = mysqli_query($dbconnection, $query);
    if (!$result) { 
        die("Database query failed");
    }
?>

当我在我的数据库中运行此查询时,它会按预期返回 3 行。在我的网页中,我首先使用 mysqli_fetch_assoc($result),它会呈现一个包含预期信息的无序列表。然后我继续使用 mysqli_fetch_row($result) 来显示更多信息,但是第二个 while 循环不会产生任何表数据(只是 th 标签的内容)。

    <h1>The Players</h1>
    <ul>
        <?php
            // Use return data with mysqli_fetch_assoc
            while($row = mysqli_fetch_assoc($result)) {
                // output data from each row
        ?>
            <li><?php echo $row["playerId"]; ?></li>
            <li><?php echo $row["fname"] . " " . $row["lname"]; ?></li>
            <li><?php echo $row["team"]; ?></li>
            <li><?php echo $row["position"]; ?></li>
        <?php echo "<hr />";
            }
        ?>
    </ul>

    <h1>The Stats</h1>
    <table>
        <th>Player</th>
        <th>Batting Avg</th>
        <th>Homeruns</th>
        <th>RBIs</th>

// DATA BELOW THIS POINT IS NOT RENDERED BY THE WEBPAGE

        <?php 
            // Use return data with mysqli_fetch_row
            while($row = mysqli_fetch_row($result)) {
        ?>
            <tr>
                <td><?php echo $row[2]; ?></td>
                <td><?php echo $row[8]; ?></td>
                <td><?php echo $row[9]; ?></td>
                <td><?php echo $row[10]; ?></td>
            </tr>
        <?php
            }
        ?>
    </table>


    <?php
        // Release returned data
        mysqli_free_result($result);
    ?>

我将在接下来的几周内为这门课编写大量的 php,所以我真的很想要一些关于如何自己解决这类错误的提示。我可以使用哪些方法轻松检查 $result 的内容以查看是否实际传递了任何资源?在我看来,第二个循环中的 $row 没有被分配给任何东西,所以它只是不执行 echo 命令。

【问题讨论】:

  • 我怀疑您已经将指针移到了结果的末尾。尝试颠倒您的 WHILE 语句,看看会发生什么。
  • 很可能,行在 assoc 循环中已经用尽了
  • @Shwheelz 你可以试试或者运行你的查询两次。
  • @Shwheelz 我认为-&gt;data_seek() 重置了指针,试试那个
  • 感谢您的帮助!在两者之间添加&lt;?php $result-&gt;data_seek(0) ?&gt; 修复它!

标签: php mysql sql


【解决方案1】:

幽灵是正确的。当您最后遍历记录时,它不会由其重新设置,它不是循环列表。因此,您必须使用 $obj->data_seek(int, ie 0); 手动将其设置为 0;或程序风格 mysqli_data_seek($result,0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-28
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多