-5

I have coded the following form with PHP & MySQL as database. I want to prevent the form from submitting data, if email address already exists in database. I also want to disable the submit button, if email exists in database.

Index.php:

    <?php
    require_once './include/user.php';
    $user_obj = new user();

    if (isset($_POST['submit'])) {
        $message = $user_obj->save_user($_POST);
    }
    ?>


    <!DOCTYPE html>

    <html>
        <head>
            <title>PHP Form With JS Validation</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" type="text/css" href="css/style.css">
            <script type="text/javascript" src="js/country.js"></script>
            <script type="text/javascript" src="js/jsval.js"></script>
        </head>
        <body>
            <p>PHP Form With JS Validation</p>

            <div id="id1">
                <form id="myForm" name="myForm" action="index.php" method="POST" onsubmit="return validateStandard(this)">
                    <table>

                        <tr><td><input type="text" name="name" value="" placeholder="name" required="required" regexp="JSVAL_RX_ALPHA"></td></tr>
                        <tr><td><input type="email" name="email" value="" placeholder="email" required="required" required regexp="JSVAL_RX_EMAIL"></td></tr>
                        <tr><td><input type="password" name="user_password" value="" placeholder="password" required="required"></td></tr>
                        <tr><td><input type="tel" name="phone" value="" placeholder="phone no" required="required"></td></tr>

                        <tr>
                            <td>
                                <input type="radio" name="gender" value="male" checked>Male
                                <input type="radio" name="gender" value="female">Female
                            </td>
                        </tr>
                        <tr><td><textarea name="address" placeholder="address" required="required"></textarea></td></tr>
                        <tr><td><input type="text" name="city" value="" placeholder="city" required regexp="JSVAL_RX_ALPHA"></td></tr>
                        <tr><td>
                                <select name="country" required="required" exclude=" ">
                                    <option value=" ">Please Select Country</option>
                                    <script type="text/javascript">printCountryOptions();</script>
                                </select>
                            </td></tr>
                        <tr><td><input type="text" name="zipcode" value="" placeholder="zipcode" required="required" regexp="JSVAL_RX_ALPHA_NUMERIC"></td></tr>

                        <tr><td><input type="checkbox" name="agree" value="on" required="required"> I agreed with all the terms!</td></tr>
                        <tr><td><input type="submit" id="sbtn" name="submit" value="Register"></td></tr>


                    </table>
                </form>
            </div>
        </body>
    </html>
    <script>
        document.forms['myForm'].reset();
    </script>

db: user.php

    <?php

    class user {

        public function save_user($data) {
            $hostname = "localhost";
            $username = "root";
            $password = "";
            $dbname = "db_user_info";

            $conn = mysqli_connect($hostname, $username, $password, $dbname);
            $user_password = md5($data['user_password']);
            $sql = "INSERT INTO tbl_user (name, email, user_password, phone, gender, address, city, country, zipcode, agree) VALUES ('$data[name]','$data[email]','$user_password', '$data[phone]','$data[gender]','$data[address]','$data[city]','$data[country]','$data[zipcode]','$data[agree]')";
            if (!mysqli_query($conn, $sql)) {
                die('Sql Error:' . mysqli_error($conn));
            } else {           
                header('Location:thanks.php');
            }
            mysqli_close($conn);
        }



    }
  • 7
    Please dont __roll your own__ password hashing. PHP provides [`password_hash()`](http://php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://php.net/manual/en/function.password-verify.php) please use them. And here are some [good ideas about passwords](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) If you are using a PHP version prior to 5.5 [there is a compatibility pack available here](https://github.com/ircmaxell/password_compat) – RiggsFolly Jan 23 '17 at 14:42
  • You would have to write some javascript and an AJAX call to a script on the server to first check if the user existed, which makes this question **Too Broad** – RiggsFolly Jan 23 '17 at 14:44
  • Possible duplicate of [check if row exists with mysql](http://stackoverflow.com/questions/22252904/check-if-row-exists-with-mysql) – Funk Forty Niner Jan 23 '17 at 14:47
  • 3
    Possible duplicate of [check username exists using ajax](http://stackoverflow.com/questions/38028854/check-username-exists-using-ajax) – Funk Forty Niner Jan 23 '17 at 14:52
  • 2
    Possible duplicate of [check username exists using ajax](http://stackoverflow.com/questions/38028854/check-username-exists-using-ajax) – 41686d6564 stands w. Palestine Jan 23 '17 at 16:02

3 Answers3

1

To achieve this you will need ajax, you have two options

  1. on the username field you can have an onblur event, then call a function that will check the username in the database using the onblur event.

<input name="username" type="text" id="username" onBlur="checkAvailability()">

The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

With this method as soon as the user finishes typing the email address and leaves the input field, the checkAvailability() function is fired up and send Asynchronous request to the server using ajax. the user will know if the username is taken even before they can submit.

  1. Collect all form data and return results when the submit button is hit without refreshing the page, (ajax as well).

Lets start with option 2 because its kinda easy.

First you will need to use prepared statements, also use php builtin password_hash and password_verify() functions for better safer passwords

lets begin, we will have a form with username field(email) only just you can see whats's happening, then when we click the register button we start our ajax that will call the php script and return json data back to use.

index.php

<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
 <script type="text/javascript">
    $(document).ready(function (){

    $('#register').submit(function (event){

    var formData = {

        'username' : $('input[name=username]').val()
    };
    $.ajax({

        type : 'POST',
        data  : formData,
        url  : 'register.php',
        dataType :'json',
        encode   : true

    })
    .done(function(data){

        console.log(data); //debugging puroposes

        if(!data.success){

          if(data.errors.username){


            $('#user-availability-status').append(data.errors.username);

          }

          if(data.errors.exists){

            $('#user-availability-status').append(data.errors.exists);
            $('#submit').prop('disabled', true);
          }
        }else{

          $('#submit').prop('disabled', false);
          $('#success').append('<div class="alert alert-success">'+data.message+'</div>');
         // alert('done');
        }

    })

    .fail(function(data){

      console.log(data); //server errrors debugging puporses only
    });

    event.preventDefault();


    });

    });

</script>
<div id="frmCheckUsername">

<div id="success" class="status-available"></div>

    <form method="POST" action="register.php" id="register">
        <label>Username:</label>
        <input name="username" type="text" id="username"><span id="user-availability-status" class="status-not-available"></span><br><br>
        <button type="submit" name="submit" id="submit"> Register </button>   
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>
</form>

Register.php

<?php
require_once("dbcontroller.php");


$data   = array();
$errors = array();

if (empty($_POST['username'])) {

    $errors['username'] = 'enter username';
} else {


    $username = $_POST['username'];

    //check if username exists
    $statement = $con->prepare("SELECT email FROM users WHERE email = ? LIMIT 1");
    $statement->bind_param('s', $username);
    $statement->execute();
    $statement->store_result();
    if ($statement->num_rows == 1) {

        $errors['exists'] = 'the email ' . $username . ' already registered please login';

    }
}

if (!empty($errors)) {

    //We have errors send them back

    $data['success'] = false;
    $data['errors']  = $errors;
} else {

    //No errors insert

    $stmt = $con->prepare("INSERT INTO users (username) VALUES(?)");
    $stmt->bind_param("s", $username);
    $stmt->execute();



    $data['success'] = true;
    $data['message'] = 'user registered';

    $stmt->close();
    $con->close();
}

echo json_encode($data);



?>

dbcontroller.php is my database connection class, so you can ignore that and have your own.

This will point you to the correct direction atleast

Option 1 using the onblur event

<style>
.status-available{color:#2FC332;}
.status-not-available{color:#D60202;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function checkAvailability() {
    $("#loaderIcon").show();
    jQuery.ajax({
    url: "register.php",
    data:'username='+$("#username").val(),
    type: "POST",
    success:function(data){
        $("#user-availability-status").html(data);
        $("#loaderIcon").hide();
        $('#submit').prop('disabled', true);
    },
    error:function (){}
    });
}
</script>

<div id="frmCheckUsername">
  <label>Check Username:</label>
  <input name="username" type="text" id="username" onBlur="checkAvailability()"><span id="user-availability-status" class="status-not-available"></span>  <br><br>

  <button type="submit" name="submit" id="submit"> Register </button>  
</div>
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

On this one as soon as the user leaves the input box the checkAvailability(); is fired up

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
-1

you just check before that email already exist in Db you just make an ajax request when user type email then make an ajax if response is true just disabled submit button

Rohit
  • 1
  • 1
  • I know you are short of reps, but this is really just a comment. This type of answer attracts downvotes or gets flagged ___I did not DV___ and if that happens you will loose rep points and take longer to get to the 50 reps you need to comment on any question. Until then, stick to questions that are well asked and therefore easily answered without needing clarification. http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead – RiggsFolly Jan 23 '17 at 14:46
  • thanks @RiggsFolly i got it. better next time – Rohit Jan 23 '17 at 14:48
-1

You must use ajax. http://api.jquery.com/jquery.ajax/

Your submit button default is disabled. After if the visitor write the e-mail address, you send the ajax query with this address to your backend, and it will return the e-mail status. If the email not exists in your database, the js remove disabled property from the button.

It's so similar like this: check username exists using ajax

Community
  • 1
  • 1
esemve
  • 360
  • 2
  • 10
  • I know you are short of reps, but this is really just a comment. This type of answer attracts downvotes or gets flagged ___I did not DV___ and if that happens you will loose rep points and take longer to get to the 50 reps you need to comment on any question. Until then, stick to questions that are well asked and therefore easily answered without needing clarification. http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead – RiggsFolly Jan 23 '17 at 14:48
  • @RiggsFolly I'm sry, i got it – esemve Jan 23 '17 at 14:52