Check if user exists

Codes here !

Moderators: egami, macek, gesf

Post Reply
minimum
New php-forum User
New php-forum User
Posts: 1
Joined: Mon Jun 08, 2020 7:01 am

Mon Jun 08, 2020 8:17 am

Hello. Have tested this code without success:

Code: Select all

<!doctype html>

  <html>

    <head>

      <?php include 'inc/css-links.php'; ?>

          <meta charset="utf-8">

            <title><?php include 'inc/title.php'; ?></title>

    </head>

<?php

  include 'inc/header.php';

  include 'inc/mysql-connection.php';

if(isset($_POST['create'])) {

  $username = mysql_real_escape_string($_POST['username']);


//check if user exists

$query = "SELECT FROM users WHERE username='$username'";

$result = mysql_query ($query);
$num_rows = mysql_num_rows ($result);

if ($num_rows > 0) { // i.e if matches were found

echo "User details already exist!";

} else {

    //check if user exists end


    $p = $_POST['password'];

    $hashed_p = password_hash($p, PASSWORD_DEFAULT);

//code for image uploading
if($_FILES['ProfileImg']['name']){

move_uploaded_file($_FILES['ProfileImg']['tmp_name'], "image/".$_FILES['ProfileImg']['name']);

$img="image/".$_FILES['ProfileImg']['name'];
}

$sql = "INSERT INTO users (username, password, firstname, lastname, email, telephone, image)
VALUES ('".$_POST["username"]."','".$hashed_p."','".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["email"]."','".$_POST["telephone"]."','".$img."')";

        if ($connect->query($sql) === TRUE) {

echo "<script type= 'text/javascript'>

        alert('New record created successfully');

    </script>";

}

else

{

    echo "<script type= 'text/javascript'>

        alert('Error: " . $sql . "<br>" . $connect->error."');

    </script>";

}
}
}

?>

<center>

<table width="1300" border="1">

  <tbody>

    <tr valign="top">

      <td width="200" rowspan="2" class="left-td"><?php include 'inc/left_td.php'; ?></td>

      <td width="900" class="profile-usernamefield">

  <?php

        include 'inc/profile-usernamefield.php';

        ?>

      </td>

      <td width="200" rowspan="2" class="right-td">

<?php

  include 'inc/login.php';

  ?>

</td>

    </tr>

    <tr>

      <td class="main-td">

        <!--<form action="register.php" method="post" enctype="application/x-www-form-urlencoded">-->

      <form action="register.php" method="post" enctype="multipart/form-data">

        <label for="username" class="form__field">Username:</label><br>

        <input type="text" name="username" required class="form__field"><br><br>


        <label for="password" class="form__field">Password:</label><br>

        <input type="password" name="password" required class="form__field" id="pwd"><br><br>


        <label for="password-repeat" class="form__field">Password repeat:</label><br>

        <input type="password" name="password" required class="form__field" id="pwd-r"><br><br>


        <label for="firstname" class="form__field">First name:</label><br>

        <input type="text" name="firstname" required class="form__field"><br><br>


        <label for="lastname"class="form__field">Lastname:</label><br>

        <input type="text" name="lastname" required class="form__field"><br><br>


        <label for="email" class="form__field">Email:</label><br>

        <input type="email" name="email" required class="form__field"><br><br>


        <label for="telephone" class="form__field">Telephone:</label><br>

        <input type="text" name="telephone" required class="form__field"><br><br>


        <label for="image" class="form__field">Image:</label><br>

        <input type="file" name="ProfileImg" required><br><br>


        <input type="submit" name="create" value="Create account" onclick="return Validate()"><br><br>

      </form>

      </td>

    </tr>

  </tbody>

</table>

</center>

 <script type="text/javascript">

    function Validate() {

        var password = document.getElementById("pwd").value;

        var confirmPassword = document.getElementById("pwd-r").value;

        if (password != confirmPassword) {

            alert("Passwords do not match.");

            return false;
        }

        return true;
    }

</script>

<center>

  <?php

  include 'inc/footer.php';
After submitting the form, only the data from the header page shows up. Header.inc contains ->

Code: Select all

<body>

<br>

<center>

<table width="1290" class="header">

  <tbody>

    <tr>

      <td  valign="top"><a href="index.php"><img src="img/IMG_1081.jpg" border="0" width="1290" height="380"></a></td>

    </tr>

  </tbody>

</table>

</center><br>
But when I remove this "check if user exists"-code, the data from the form goes in to the database. What am I missing here?
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 396
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Mon Jun 08, 2020 10:03 am

I can never understand why people use a table in a form? This is my form that I use for my trivia game:

Code: Select all

        <div id="registrationPage">
            <form class="registerForm" action="" method="post" autocomplete="on">

                <h1><?php echo (isset($message)) ? $message : 'Register'; ?></h1>
                <p><?php echo (isset($errPassword)) ? $errPassword : "Please fill in this form to create an account."; ?></p>
                <hr>

                <label for="username"><b>Username <span class="unavailable"> - Not Available, please choose a different one.</span></b></label>
                <input id="username" type="text" placeholder="<?php echo (isset($statusUsername) && $statusUsername) ? "Username is not available, please re-enter!" : "Enter Username"; ?>" name="data[username]" value="<?php echo (isset($data['username'])) ? $data['username'] : null; ?>" autofocus required>

                <label for="email"><?php echo (isset($errEmail)) ? $errEmail : "<b>Email</b>"; ?></label>
                <input type="email" placeholder="Enter Email" name="data[email]" value="<?php echo (isset($data['email'])) ? $data['email'] : null; ?>" required>

                <label for="psw"><b>Password <span class="recommendation">recommendation at least (8 characters long, 1 uppercasse letter, 1 number, and 1 special character)</span></b></label>
                <input id="password" type="password" placeholder="Enter Password" name="data[password]" required>

                <label for="psw-repeat"><b>Repeat Password</b></label>
                <input type="password" placeholder="Repeat Password" name="data[repeatPassword]" required>
                <hr>

                <p>By creating an account you agree to our <a href="termsPolicy.php">Terms & Privacy</a>.</p>
                <input type="submit" name="submit" value="enter" class="registerbtn">


                <div class="signin">
                    <p>Already have an account? <a href="index.php">Sign in</a>.</p>
                </div>
            </form>
        </div>
        <script src="assets/js/register.js"></script>
    </body>
</html>
Use prepared statements and PDO to do the check:

Code: Select all

function duplicateUsername($username, $pdo) {
    $query = "SELECT 1 FROM users WHERE username = :username";
    $stmt = $pdo->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $row = $stmt->fetch();
    if ($row) {
        return true; // userName is in database table
    }
}
and you really should have an unique filed in your MySQL Table and catch it with a Try-Catch Block if you want to do it properly:

Here how I do that for my website: (Sorry about the OOP)

Code: Select all

    public function register($data, $status) {
        $db = DB::getInstance();
        $pdo = $db->getConnection();
        $this->pwd = password_hash($data['password'], PASSWORD_DEFAULT);
        unset($data['password']); // $this-pwd is private argument/variable:
        try {
            $this->query = 'INSERT INTO users (username, status, password, security, email, date_added) VALUES (:username, :status, :password, :security, :email, Now())';
            $this->stmt = $pdo->prepare($this->query);
            $this->result = $this->stmt->execute([':username' => $data['username'], ':status' => $status, ':password' => $this->pwd, ':security' => 'newuser', ':email' => $data['email']]);
        } catch (\PDOException $e) {

            //echo "unique index" . $e->errorInfo[1] . "<br>";
            // an error occurred
            /*   if the error number is for something that this code is designed to handle, i.e. a duplicate index, handle it by telling the user what was wrong with the data they submitted
              // failure due to a specific error number that can be recovered from by the visitor submitting a different value
              return false;
              else
              // the error is for something else, either due to a programming mistake or not validating input data properly, that the visitor cannot do anything about or needs to know about
              throw $e; // re-throw the exception and let the next higher exception handler, php in this case, catch and handle it
             * 
             */
            if ($e->errorInfo[1] === 1062) {
                return false;
            } else {
                throw $e;
            }
        } catch (Exception $e) {
            echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server:
        }

        return true;
    }
That way there is no definite way a user can have the same username as someone else unless you had a really really busy website where it would be possible that two people could add that username at the exact time. Though you would have to be as big as Facebook or Amazon.
Life is a fig newton of your imagination! https://www.miniaturephotographer.com
Post Reply