尝试访问类型为bool的值的数组偏移量 [英] Trying to access array offset on value of type bool

查看:274
本文介绍了尝试访问类型为bool的值的数组偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$query = $pdo -> prepare("SELECT * FROM Users WHERE Username =:Username");
$query->bindParam(':Username', $name);
$query->execute();

$nameRes = $query->fetch(PDO::FETCH_ASSOC);
if ($nameRes['Username']==$_POST['username']) {
    die ("Username is already in use!");
}   

$query = $pdo -> prepare("SELECT * FROM Users WHERE Email =:Email");
$query->bindParam(':Email', $email);
$query ->execute();
$emailRes = $query->fetch(PDO::FETCH_ASSOC);

if ($emailRes['Email']==$_POST['email']) {
    die ("Email is already in use!");
}

我在我的应用程序的注册页面上有此代码,并且当用户名可以免费使用但电子邮件不可用时,反之亦然,我会得到

I have this code on the registration page of my app and when Username is free to use but email is not and vice versa I get this

注意:尝试访问类型为bool的值的数组偏移量

Notice: Trying to access array offset on value of type bool

好吧,结果返回false,但是在这种情况下该怎么办?注意:这是在php v7.4上,这同样在v7.3上工作

Ok the result is returning false but what to do in this situation? Note: This is on php v7.4 this same thing was working on v7.3

推荐答案

您会收到此错误,可能是因为在数据库中找不到符合您条件的记录.

You are getting this error probably because there were no records found in the database matching your criteria.

这不是使用PDO检查数据库中是否存在的方式.正确的方法是:

This is not how you would check for existance in DB using PDO. The correct way would be:

$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Username =:Username");
$query->execute([':Username' => $name]);
if ($query->fetchColumn()) {
    throw new \Exception("Username is already in use!");
}

$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Email =:Email");
$query->execute([':Email' => $email]);
if ($query->fetchColumn()) {
    throw new \Exception("Email is already in use!");
}

不是从PHP中获取行并再次进行比较,而是从数据库中获取匹配行的计数,并在if语句中将该计数用作布尔值. fetchColumn()将从第一行中提取单个列,如果我使用COUNT(*),我知道将总是有一行.

Instead of fetching the row and doing the comparison again in PHP I am fetching a count of matching rows from the database and I use that count as a boolean in the if statement. fetchColumn() will fetch a single column from the first row and if I use COUNT(*) I know there will always be one row.

您也可以在一个查询中做到这一点:

You can also do it in one query:

$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Username =:Username OR  Email =:Email");
$query->execute([':Username' => $name, ':Email' => $email]);
if ($query->fetchColumn()) {
    throw new \Exception("Username or email is already in use!");
}

这篇关于尝试访问类型为bool的值的数组偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆