简体   繁体   English

检查用户名,电子邮件是否已存在于mysql数据库中

[英]Check if username, email already exists in mysql db

I'm trying to check if an username or an email already exists in my database, sadly it wont work. 我正在尝试检查数据库中是否已经存在用户名或电子邮件,可惜它无法正常工作。

Does anyone have an idea where I'm failing? 有人知道我要失败吗?

My code: 我的代码:

<?php
    require_once('handling/database.php');
    if(!empty($_POST)){
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $database = new database;
        $database->connect();

        $user_check = $database->execute_query("SELECT * FROM Users WHERE Username = '" . $username . "'");
        $email_check = $database->execute_query("SELECT * FROM Users WHERE Email = '" . $email . "'");

        if($user_check && mysql_num_rows($user_check) > 0){
            echo 'The following username is already in use: ' . $username;
        }else if($email_check && mysql_num_rows($email_check) > 0){
            echo 'The following email is already in use: ' . $email;
        }else{
            $results = $database->execute_query("INSERT INTO Users (Username, Email, Password) VALUES ('" . $username . "', '" . $email . "', '" . $password . "')");
            if($result = 'false'){
                echo 'The following account was created: ' . $username;
            }else{
                echo 'Error: Could not create the following account: ' . $username;
            }
        }
    }
?>

And the execute_query function from my database.php class: 还有来自我的database.php类的execute_query函数:

function execute_query($sql) {
  if ( $results = $this->_mysqli->query($sql) ) {
     return $results;
  }
  else {
     return false;
  }
}

The account creation works fine, the username check and email check doesn't. 帐户创建工作正常,用户名检查和电子邮件检查不起作用。

Since the database class uses the mysqli extension, you can't use mysql_XXX functions with it. 由于database类使用mysqli扩展名,因此您不能对其使用mysql_XXX函数。 You need to use mysqli_num_rows . 您需要使用mysqli_num_rows

if ($result = 'false')

has two problems: First, you have to use == or === to compare values, = is for assignment. 有两个问题:首先,您必须使用=====比较值, =是用于赋值。 Second, 'false' is a string because you put it in quotes, but the function returns the boolean value false . 其次, 'false'是一个字符串,因为您将其放在引号中,但该函数返回布尔值false It should be: 它应该是:

if ($result == false)

or simple: 或简单:

if (!$result)

Another problem is that the variable you assign from the query is $results , but then you test $result (no s at the end). 另一个问题是,您从查询分配的变量是$results ,但是随后您测试了$result (末尾为s )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM