如何单独检查数据库中是否存在PHP用户名或电子邮件

时间:2017-10-07 15:59:31

标签: php mysql sql mysqli

现在我的代码检查数据库中是否存在用户名和电子邮件变量,因为它们都是唯一键,但是我如何制作它以便我可以单独检查每个变量并输出不同的响应?

例如,如果用户名存在 - > “那个用户名已经存在。” 或者,如果电子邮件存在,但用户名不存在 - > “那封电子邮件已经存在。”

<?php
  include 'include/connection.php';

  $username = mysqli_real_escape_string($conn, $_REQUEST['username']);
  $password = mysqli_real_escape_string($conn, $_REQUEST['password']);
  $name = mysqli_real_escape_string($conn, $_REQUEST['name']);
  $email = mysqli_real_escape_string($conn, $_REQUEST['email']);

  $sql = "INSERT INTO userdata (username, password, name, email) VALUES ('$username', '$password', '$name', '$email')";

  if (mysqli_query($conn, $sql)) {
    echo "Your account was created successfully, please login to continue.";
    echo '<form action="login.php">
            <input type="submit" name="login" id="login" value="Login" />
          </form>';
  } else {
    echo "That username already exists, please try again.";
    echo '<form action="registration.php">
            <input type="submit" name="register" id="register" value="Register" />
          </form>';
  }
?>

3 个答案:

答案 0 :(得分:1)

使用函数和编写SQL以检查emailusername两者的可能方法之一。

SELECT username, email from userdata where username = ? OR email = ?

并循环遍历结果集并检查是否存在emailusername并相应地返回错误消息。

答案 1 :(得分:0)

试试这个

 $checkUserNameSql = "Select Count(username) as username from userdata WHERE username = '".$username."'";

$result=mysql_query($checkUserNameSql);
$data=mysql_fetch_assoc($result);

echo $data['username'];

如果你得到一个计数,你可以对它进行检查。

答案 2 :(得分:-1)

在代码下方使用。首先,您需要检查用户名和电子邮件,然后插入记录。

include 'include/connection.php';
$username = mysqli_real_escape_string($conn, $_REQUEST['username']);
  $password = mysqli_real_escape_string($conn, $_REQUEST['password']);
  $name = mysqli_real_escape_string($conn, $_REQUEST['name']);
  $email = mysqli_real_escape_string($conn, $_REQUEST['email']); 

  $checkUser    = 'select  email ,username from userdata where email="'.$email.'" or username = "'.$username.'"';
  $result       = mysqli_query($conn,$checkUser);
  $row          = mysqli_fetch_assoc($result);
  if(!empty($row)){
    if($row['email']==$email){
        echo "That email already exists. Please try again";
    }
    else if($row['username']==$username){
        echo "That username already exists. Please try again";
    }

    echo '<form action="registration.php">
        <input type="submit" name="register" id="register" value="Register" />
      </form>';
  }
  else{

    $sql = "INSERT INTO userdata (username, password, name, email) VALUES ('$username', '$password', '$name', '$email')";
    if (mysqli_query($conn, $sql)) {
    echo "Your account was created successfully, please login to continue.";
    echo '<form action="login.php">
            <input type="submit" name="login" id="login" value="Login" />
          </form>';
     }
  }