PHP for mySQL check if user exists

I have a script that updates / creates a user from an iOS device. Now I want the script to also check if the user exists in the database. For now, I will restrict this username, so there cannot be more than one unique username. I have an if-statement in my PHP, but I cannot get it to work - please help :).

    <?php

    header('Content-type: application/json');
    if($_POST) {
        $username   = $_POST['username'];
        $password   = $_POST['password'];

        if($username && $password) {

                $db_name     = 'dbname';
                $db_user     = 'dbuser';
                $db_password = 'dbpass';
                $server_url  = 'localhost';

                $mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);

            $userexists = mysql_query("SELECT * FROM users WHERE username='$username'"); 

            /* check connection */
            if (mysqli_connect_errno()) {
                error_log("Connect failed: " . mysqli_connect_error());
                echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
            }

            if(mysql_num_rows($userexists) != 0) { 
                echo '{"success":0,"error_message":"Username Exist."}';
            } 

            else {

                $stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
                $password = md5($password);

                $stmt->bind_param('sss', $username, $password, $email);

                    /* execute prepared statement */
                $stmt->execute();

                if ($stmt->error) {error_log("Error: " . $stmt->error); }

                $success = $stmt->affected_rows;

                    /* close statement and connection */
                $stmt->close();

                    /* close connection */
                $mysqli->close();
                error_log("Success: $success");

                        if ($success > 0) {
                        error_log("User '$username' created.");
                        echo '{"success":1}';
                        } 
                        else {
                        echo '{"success":0,"error_message":"Username Exist."}';
                        }
            }

        } 
        else {
            echo '{"success":0,"error_message":"Passwords does not match."}';
        }
    } 
    else {
        echo '{"success":0,"error_message":"Invalid Username."}';
    }
}   
else {
    echo '{"success":0,"error_message":"Invalid Data."}';
}
?>

      

0


source to share


1 answer


You may SELECT

want tables before you insert username

. If it already exists (= you have a result), you just don't insert.



Better yet, use ON DUPLICATE IGNORE

or something like that.

0


source







All Articles