PHP 7.2 - 警告:count():参数必须是实现 Countable 的数组或对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51594817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:52:51  来源:igfitidea点击:

PHP 7.2 - Warning: count(): Parameter must be an array or an object that implements Countable

phpphp-7.2

提问by Marwan Khaled

I just upgraded my PHP Versionfrom 5.6to 7.2. I used count()function in my login page, example:

我刚刚将我的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;

After searching, I found questions and answers similar to this one but they were related to WordPress that they modified some files, but I couldn't find a solution for it using Pure PHP.

搜索后,我发现了与此类似的问题和答案,但它们与 WordPress 相关,他们修改了一些文件,但我无法使用Pure PHP找到解决方案。

回答by Olim Saidov

PDO fetchreturns false on failure. So you need to check this case too:

PDOfetch在失败时返回 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';
}