【问题标题】:PHP if else while (with mysql) statement not workingPHP if else while (with mysql) 语句不起作用
【发布时间】:2023-03-15 21:50:01
【问题描述】:

我的函数中有这段代码,如果它无法获取存储在变量 $result 中的数据,它会回显“Empty”。 “空”部分工作正常。但是,如果条件进入else部分,它不会回显用户数据,为什么?

$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT ".$load.",1") or die (mysql_error());
if(!mysql_fetch_row($result)) {
    echo "Empty";
} else {
    while($data = mysql_fetch_array($result))
    {
        if($name == true) {
            echo ucfirst($data['user']);
        } else {
            echo ucfirst($data['earnings']);
        }
    }
}

【问题讨论】:

  • 什么是$name?另请记住,mysql_*() 函数已被弃用多年且不受支持。更改您的代码!
  • @miken32 我函数中的一个变量。 (此代码是我的功能的一部分)。

标签: php mysql sql conditional


【解决方案1】:

通过调用mysql_fetch_row($result) 作为测试,您总是会丢失第一行数据。检查行数是否为 0。

【讨论】:

  • 请更新您的代码以停止依赖多年未更新的功能。您可能可以在半小时内更新您的代码以使用mysqli_*()
【解决方案2】:

试试这个

$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT ".$load.",1") or die (mysql_error());
    if(!$result) {
        echo "Empty";
    } else {
        while($data = mysql_fetch_array($result))
        {
            if($name == true) {
                echo ucfirst($data['user']);
            } else {
                echo ucfirst($data['earnings']);
            }
        }
    }

【讨论】:

  • 完全没有解释。没有迹象表明发生了什么变化或出了什么问题。这是勺子喂食。
【解决方案3】:

您好,我认为您的问题在 mysql_fetch_array() 中。此函数将返回数组而不是关联数组..

你可以使用

$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT    ".$load.",1") or die (mysql_error());
if(mysql_num_rows($result) == 0) {
   echo "Empty";
} else {
     while($data = mysql_fetch_array($result,MYSQL_BOTH))
 {
    if($name == true) {
        echo ucfirst($data['user']);
    } else {
        echo ucfirst($data['earnings']);
    }
 }
}

使用 mysql_num_rows 而不是 mysql_fetch_row 来检查空记录集。

我在 mysql_fetch_array 中传递了第二个参数,MYSQL_BOTH 将返回数组和关联数组..

或者你可以使用

mysql_fetch_assoc() 函数代替 mysql_fetch_array()..

欢迎提问..

【讨论】:

  • mysql_fetch_array() 两者都返回。
  • 迈克你是对的,它同时返回,但是当你在我的解决方案中传递第二个参数 MYSQL_BOTH 时..
  • MYSQL_BOTH 是默认设置。
  • @miken :我将 mysql_fetch_row 更改为 mysql_num_rows 这将解决他的问题..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多