【问题标题】:PHP SQL loop outputs as 0 rowsPHP SQL 循环输出为 0 行
【发布时间】:2015-03-01 23:37:05
【问题描述】:

我正在尝试创建一个 PHP 循环来向玩家展示他们正在参加的锦标赛。我在 phpMyAdmin 上尝试了该功能,得到了我想要的结果。但是当我尝试在 PHP 上运行这个简单的脚本时,它输出为 0 行。

index.php

chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");

if($mybb->user['uid']) {
    $sql = "SELECT * FROM players, tourneys WHERE players.forumname = 1 AND players.tid = tourneys.id";
    $result = mysqli_query($conn, $sql);
    // output data of each row
    if (mysqli_num_rows($result) > 0) {
        // output data of each ro
        while($row = mysqli_fetch_assoc($result)) {
            $name = $row['name'];
            $date = $row['date'];
            $time = $row['time'];
            echo $name;
            echo $date;
            echo $time;
        }
    } else {
        echo "0 rows";
    }
}

【问题讨论】:

  • if($mybb->user['uid']) 该条件正在停止查询
  • 您还可以添加一个 Try-Catch 块来处理如果查询返回 0 行可能导致的异常错误。

标签: php mysql sql database loops


【解决方案1】:

问题不在于@Dagon 建议的“if ($mybb->user['uid']) {”。尽量保留缩进良好的代码以避免这种混淆。运行下面的代码并发布 DB 错误输出。

试试这个:

<?php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");

if ($mybb->user['uid']) {

    $player_forumname = '1';

    // Return only the necessary fields
    $sql = "SELECT tourneys.name, tourneys.date, tourneys.time
            FROM tourneys
            INNER JOIN players ON players.tid = tourneys.id
            WHERE players.forumname = {$player_forumname}";

    $result = mysqli_query($conn, $sql);

    // If the query fails display the error
    if ($result === FALSE) {
        die('MySQLi Error: ' . mysqli_error($conn));
    }

    if (mysqli_num_rows($result) == 0) {
        die('0 rows');
    }

    // Returns only the associative array
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $name = $row['name'];
        $date = $row['date'];
        $time = $row['time'];

        echo 'Name:',$row['name'],'Date:',$row['date'],'Time:',$row['time'];
    }
}

【讨论】:

  • 没有输出错误,只是说“0行”。我能够通过 phpMyAdmin 运行查询,没有任何问题。我有一条消息说“当前选择不包含唯一列。网格编辑、复选框、编辑、复制和删除功能不可用。”
  • 您是否尝试过 Gustavo 的建议(即使用 INNER JOIN)?你真的想要这个where clause吗?即` WHERE player.forumname = 1` where 子句似乎不对
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多