我想检查我的注册脚本中是否有用户名和电子邮件。
这是我查询的方式:
$emailcheck = "SELECT COUNT(email) AS nume FROM members WHERE email = :email";
//bindValue
//execute
//fetch
if($rowe['nume'] > 0){
$errors[] = "E-mail exist.";
}
而且我也在为用户名做同样的事情;
$usercheck = "SELECT COUNT(username) AS numu FROM members WHERE username = :username";
//bindValue
//execute
//fetch
if($rowu['numu'] > 0){
$errors[] = "Username taken.";
}
*
我想更进一步,用一个查询处理所有内容。
但我无法想出这样的问题。
我试过了:
$check = "SELECT COUNT(username) AS numu and COUNT(email) AS nume FROM members WHERE username = :username OR email = :email";
但可能是荒谬的。
如何使用一个查询处理我想要的内容?
在我想要检查之后:
if($row['numu'] > 0){
$errors[] = "Username taken.";
}
if($rowe['nume'] > 0){
$errors[] = "E-mail exist.";
}
因此代码更少,而不是第二次将同一个表连接到bindValue, execute, fetch
。
答案 0 :(得分:3)
您可以Union All
联合这些查询:
SELECT COUNT(email) AS num FROM members WHERE email = :email
UNION ALL
SELECT COUNT(username) AS num FROM members WHERE username = :username
然后按行提取2个。
OR,MySQL允许这件事:
SELECT
(SELECT COUNT(email) FROM members WHERE email = :email) as nume,
(SELECT COUNT(username) FROM members WHERE username = :username) as numu
如果你想要1行2列。
只有当您需要查看哪一个已经存在时才这样做。否则就这样做:
SELECT 1 FROM members WHERE email = :email OR username = :username LIMIT 1
是的,请考虑不要count()
,因为您不需要计算所有行数。如果你只找到一个,你只需要停下来。因此要么LIMIT
或IF EXISTS()
答案 1 :(得分:3)
我认为你真的不需要数数。假设您要检查用户名或电子邮件是否已存在,因为它们在用户表中必须是唯一的,您可以这样做:
首先,为数据库中的每个列添加唯一索引。您可能已经拥有了这个,但如果您希望这些值是唯一的,这将确保即使您的PHP代码由于某种原因而无法执行此操作。
然后您可以使用此查询:
SELECT username, email FROM members WHERE username = :username OR email = :email
这将返回零行,一行或两行,其中:
然后,您可以循环搜索结果,将其与用户输入进行比较,并设置错误。
while ($row = //fetch) {
if ($row['username'] == $username) {
$errors[] = "Username taken.";
}
if ($row['email'] == $email) {
$errors[] = "E-mail exist.";
}
}
答案 2 :(得分:0)
您可以在计数
之间删除and
后尝试此操作
$check = "SELECT COUNT(username) AS uname ,
COUNT(email) AS uemail FROM members
WHERE (username = :username OR email = :email)";