如何使用 pdo 在一个查询中对两个值进行 rowCount?

我正在尝试创建一个注册页面,并且需要验证用户名和电子邮件是否已经退出。


如果我在两个查询中执行此操作,它可以正常工作,但切换到一个查询,则它无法正常工作,有时它不会验证值之一。


我尝试如下,但它不能正常工作,有时它不验证电子邮件或用户名:


  $uname = $_POST['username'];

  $email = $_POST['email'];


    $sql = "SELECT uid FROM users WHERE username = :username OR email = :email";

    $stmt1 = $pdo->prepare($sql);

    $stmt1->bindParam(":username", $uname, PDO::PARAM_STR);

    $stmt1->bindParam(":email", $email, PDO::PARAM_STR);

    $stmt1->execute();

    if($stmt1->rowCount() == 1){

    $rows = $stmt1->fetch();


      if($rows['username'] == 1){

        $errors['username'] = "Username already in use.";

      }else{

        $username = $uname;

      }

      if($rows['email'] == 1){

        $errors['email'] = "Email already in use.";

      }else{

        $email= $email;

      }

    }

    unset($stmt1);


临摹微笑
浏览 71回答 2
2回答

qq_笑_17

rowCount当用户名或电子邮件匹配时,方法返回 >= 1 条记录。试试那个代码:$username = $_POST['username'];$email = $_POST['email'];$errors = array();$sql = "SELECT username, email FROM users WHERE username = :username OR email = :email";$stmt1 = $pdo->prepare($sql);$stmt1->bindParam(":username", $username, PDO::PARAM_STR);$stmt1->bindParam(":email", $email, PDO::PARAM_STR);$stmt1->execute();if($stmt1->rowCount() > 0){    $rows = $stmt1->fetchAll();    foreach($rows as $row) {        if($row['username'] === $username) {            $errors['username'] = "Username already in use.";        }        if($row['email'] === $email) {            $errors['email'] = "Email already in use.";        }    }    $stmt1->closeCursor();}

绝地无双

你只是从这个查询中得到计数$sql = "SELECT uid FROM users WHERE username = :username OR email = :email";代替$sql = "SELECT uid,count(uid) FROM users WHERE username = :username OR email = :email";希望它对单个查询有所帮助
打开App,查看更多内容
随时随地看视频慕课网APP