我正在尝试检查数据库中是否存在用户名或电子邮件,并将数据返回给用户,说明电子邮件或用户名或两者是否已在使用中,有什么方法可以在不对数据库进行两次咨询的情况下做到这一点?现在我有这个↓,但我不确定它是否正确。
<?php
if (isset($_POST['sub'])){
require_once 'conexio.php';
$pdo = new Conexio();
$pdo->exec("set names utf8");
$dbTabla="usuaris";
$contra = $_POST["contra"];
$consulta=$pdo->prepare("SELECT username,email FROM $dbTabla WHERE username=? OR email=?");
$consulta->execute(array($_POST['username'],$_POST['email']));
$result = $consulta->fetchObject();
if($consulta->rowCount()>0){
if("what to put in here?"){
echo "That username it's already in use";
}
if("what to put in here?"){
echo "That e-mail it's already in use";
}
}
}
?>
谢谢
您当前查询(以及 Chinnu 建议的解决方案)的"问题"是它可能返回最多两行(一行与用户名匹配,另一行与电子邮件匹配),您可能需要迭代,这可能有点烦人。
您可以使用 BIT_OR
聚合函数获得单行结果:
$consulta=$pdo->prepare("SELECT BIT_OR(username = ?) AS username_exists, " .
"BIT_OR(email = ?) AS email_exists " .
"FROM $dbTabla " .
"WHERE username=? OR email=?");
$consulta->execute(array($_POST['username'], $_POST['email'],$_POST['username'], $_POST['email']));
现在,您有一行包含可以轻松计算的真/假表达式:
if($result->username_exists) {
echo "That username is already in use";
}
if($result->email_exists) {
echo "That e-mail is already in use";
}
你能试试这个吗,
$result = $consulta->fetchObject();
if($result->username==$_POST['username']){
echo "That username it's already in use";
}
if($result->email==$_POST['email']){
echo "That e-mail it's already in use";
}