简体   繁体   中英

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:

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. You need to use 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 . 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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