-3

I asked this question already (but it is with another question). Please refer to this thread and see what I am talking about to. Please don't say that I should use PDO or improved MySQLi because I'm gonna change it as soon as I start learning about it.

What if I want other fields to be "checked" if it already exists? My code is just working fine but it is just for the username, I also want to check if the Email Address is already taken or other fields too.

My Code:

<?php
    require_once("functions.php");
    require_once("db-const.php");
    session_start();

    if (logged_in() == true) {
        redirect_to("profile.php");
    }

    $errors=array();



    if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
      if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email'])) {
                echo "Please fill all the fields!";

}
                elseif( isset( $_POST['username'], $_POST['password'], $_POST['first_name'], $_POST['last_name'], $_POST['email'] ) ) {




            $username   = !empty( $_POST['username'] ) ? $_POST['username'] : false;
            $mainpass   = !empty( $_POST['password'] ) ? $_POST['password'] : false;
            $password   = !empty( $mainpass ) ? hash('sha256', $mainpass) : false;
            $first_name = !empty( $_POST['first_name'] ) ? $_POST['first_name'] : false;
            $last_name  = !empty( $_POST['last_name'] ) ? $_POST['last_name'] : false;
            $email      = !empty( $_POST['email'] ) ? $_POST['email'] : false;

            if( $username && $password ){
                $mysqli = new mysqli(localhost, root, "", loginsecure);
                if( $mysqli->connect_errno ) {
                    $errors[]=$mysqli->connect_error;
                } else {

                    /* Assume all is ok so far */
                    $sql='select username from users where username=?';
                    $stmt=$mysqli->prepare($sql);
                    $stmt->bind_param('s',$username);
                    $stmt->execute();

                    $stmt->bind_result( $found );
                    $stmt->fetch();

                    if( !$found ){
                        /* username is not alreday taken */

                        $sql='insert into `users` (`username`,`password`,`first_name`,`last_name`,`email`) values (?,?,?,?,?);';
                        $stmt=$mysqli->prepare( $sql );
                        $stmt->bind_param('sssss',$username,$password,$first_name,$last_name,$email);
                        $stmt->execute();

                        header("Location: checklogin.php?msg=Registered Successfully!");
                    } else {
                        /* username is taken */
                        $errors[]='Sorry, that username is already in use.';
                    }
                }
            }
        } else {
            $errors[]='Please fill in all details';
        }
    }
?>
<html>
    <head>
        <title>Prospekt Member Area</title>
    </head>
    <body>
        <h1> Register Here </h1>
        <h2>&copy; Kirk Niverba</h2>
        <hr />

        <!-- The HTML registration form -->
        <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
            Username: <input type="text" name="username" /><br />
            Password: <input type="password" name="password" /><br />
            First name: <input type="text" name="first_name" /><br />
            Last name: <input type="text" name="last_name" /><br />
            Email: <input type="type" name="email" /><br />

            <input type="submit" name="submit" value="Register" />
            <a href="login.php">Already have an account?</a>
        </form>
        <?php
            if( !empty( $errors ) ){
                echo implode( '<br />', $errors );
            }
        ?>
        <hr />
    </body>
</html>

This is not a duplicate question, the question in here is how to check it in single query not in multiple queries, and i'm also asking here if how do I use different error messages.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
virtualAnon
  • 141
  • 1
  • 1
  • 12
  • "Please don't say that I should use "PDO" or improved MySQLi because i'm gonna change it as soon as I start learning about it" - you are already using mysqli + prepared statements, so it is totaly fine – Philipp Aug 01 '16 at 09:59
  • Thanks for the comment, however, i'm looking for like a "tutorial" or explaining how it is and how does it work, and can I use a single query just to check the username or password? (but I can do multiple queries if it needs to) – virtualAnon Aug 01 '16 at 09:59
  • 1
    You could also use only one query, just use `OR` in the `where` clause for each field you want to check. `where username = ? or email = ? or x = y` – Philipp Aug 01 '16 at 10:00
  • Sorry if I've said that, because i'm a pretty starter for these things, and in my code is just selects "username from users". Does this code however works without selecting "email from users"? – virtualAnon Aug 01 '16 at 10:02
  • 1
    Yes, the `where` part words independent from the fields you are selecting, in select you choose which columns of the selected rows should be shown, in the where you only filter which rows are shown by the criteria you define – Philipp Aug 01 '16 at 10:03
  • Thanks @Philipp and MuthaFury, but last question, how does I use different error messages for the code? Example: The username is already taken; - Error message when the username is taken; The email is already taken - Error message when the email address is already taken. – virtualAnon Aug 01 '16 at 10:10
  • Then you can check the question I linked, it shows how you can check for those fields separately, define the error message and stop the insert if there is a field already – Philipp Aug 01 '16 at 10:51

1 Answers1

2

Change the query into this and then check every row returned

$sql='select username, email from users where username=? OR email=?';
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('ss',$username,$email);
$stmt->execute();
$result = $stmt->get_result();
$errors = [];
while ($row = $result->fetch_assoc()) {
    if ($row['username'] === $username) {
        $errors[] = "Username is taken";
    }
    if ($row['email'] === $email) {
        $errors[] = "Email is taken";
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
MuthaFury
  • 805
  • 1
  • 7
  • 22