【问题标题】:PHP infinite loop issuePHP无限循环问题
【发布时间】:2014-09-03 08:52:48
【问题描述】:

我可以让正确的代码工作,但我希望能够使用对象和方法,但这是行不通的。重复数据库中的相同条目,直到查询崩溃。我看到其他人在 while 语句中有查询,但我认为我使用的方法应该只查询语句一次,但我可能错了。谢谢。

<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
    $time           = $row['Time'];
    $moderator      = $row['Moderator'];
    $reason         = $row['Reason'];

    // Now for each looped row

    echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

分班

public function __construct(){
        $this->con = mysqli_connect("localhost","root","pass","Minecraft");
        // Check connection
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
    }

    public function getUUID($username) {
        $result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
        return mysqli_fetch_array($result)[0];
    }

    public function getReports($username) {
        $result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
        return $result;
    }

【问题讨论】:

  • 您需要将$MySQL-&gt;getReports('jackginger') 存储在一个单独的变量中,然后用mysqli_fetch_array($your_temp_var) 调用它。
  • 仅仅是因为查询被一遍又一遍地调用吗?
  • 是的,原因是因为您告诉 $row 等于 mysqli 将获取的第一个元素。如果它有多个项目,它将继续获取第一个项目并且永远不会停止。即使它只有一项,它也会继续获取,因为它永远不会到达 $row === false;

标签: php mysql database mysqli


【解决方案1】:

每次您调用 while($row = mysqli_fetch_array($MySQL-&gt;getReports('jackginger'))) 时,您都在进行新的查询,因此它会一遍又一遍地获取相同的内容。

解决方案可能是:

<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
    $time           = $row['Time'];
    $moderator      = $row['Moderator'];
    $reason         = $row['Reason'];

    // Now for each looped row

    echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

【讨论】:

    猜你喜欢
    • 2012-10-29
    • 1970-01-01
    • 2011-07-23
    • 2021-09-02
    • 2020-09-09
    • 2021-09-11
    • 2018-09-24
    • 1970-01-01
    相关资源
    最近更新 更多