【问题标题】:PHP 7.2 - Warning: count(): Parameter must be an array or an object that implements Countable [closed]PHP 7.2 - 警告:count():参数必须是实现 Countable 的数组或对象 [关闭]
【发布时间】:2019-01-06 18:06:15
【问题描述】:

我刚刚将我的 PHP 安装版本从 5.6 升级到了 7.2。我在登录页面上使用了count() 函数,如下所示:

if (!empty($_POST['username']) && !empty($_POST['password'])):
    $records = $conn->prepare('SELECT id,username,password FROM users WHERE username = :username');
    $records->bindParam(':username', $_POST['username']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $message = '';
    
    if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
        $_SESSION['user_id'] = $results['id'];
        header("Location: /");
    } else {
        $message = 'Sorry, those credentials do not match';
    }
endif;

经过搜索,找到了和这个类似的问题和答案,但是都和WordPress有关,找不到Pure PHP的解决方案。

【问题讨论】:

标签: php session post count php-7.2


【解决方案1】:

PDO fetch 在失败时返回 false。所以你也需要检查这种情况:

if ($results && count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
    $_SESSION['user_id'] = $results['id'];
    header("Location: /");
} else {
    $message = 'Sorry, those credentials do not match';
}

【讨论】:

  • 不是'可能失败时返回false',它失败时返回false:'这个函数成功时的返回值取决于获取类型。在所有情况下,失败都会返回 FALSE。'
  • @Script47谢谢,已相应更新。
  • 你可以使用 !is_null() 来解决这个问题。
  • count($results) > 0$results 之后的不必要/冗余检查,对吧?
  • 你也可以使用 >> error_reporting(error_reporting() & ~E_WARNING);使警告沉默
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 2018-12-19
  • 1970-01-01
  • 2018-09-10
  • 2020-01-18
  • 2019-06-20
  • 2019-10-18
  • 2019-04-29
相关资源
最近更新 更多