2

I try to check the duplicate 'username' from the database and I want to sent message back to user if username existed by using the AJAX. Until now, its only insert the data and the validation still not work. Any help are welcome, thanks!

Edited :

I'm using '$.jcrowl' to get the feedback (refer add_user.php) when the data have inserted it will pop out the feedback (Eg : 'User successfully added'). So how to apply for this 'duplicate username found in database' into this $.jcrowl, how I need to sent the validation from 'save_user.php' back to 'add_user.php'?

add_user.php

   <div class="row-fluid">
                    <!-- block -->
                    <div class="block">
                        <div class="navbar navbar-inner block-header">
                            <div class="muted pull-left"><i class="icon-plus-sign icon-large"></i> Add Admin User</div>
                        </div>
                        <div class="block-content collapse in">
                            <div class="span12">
                            <form method="post" id="add_user">
                                    <label>First Name :</label>
                                    <input class="input focused" name="firstname" id="focusedInput" type="text" placeholder = "Firstname" required>
                                    <label>Last Name :</label>
                                    <input class="input focused" name="lastname" id="focusedInput" type="text" placeholder = "Lastname" required>
                                    <label>User Type :</label>
                                    <select name="user_type" class="input focused" required/>
                                         <option></option>
                                         <?php $user_level=mysql_query("select * from user_level")or die(mysql_error()); 
                                         while ($row=mysql_fetch_array($user_level)){                                               
                                         ?>
                                         <option value="<?php echo $row['user_type']; ?>"><?php echo $row['type_name']; ?></option>
                                         <?php } ?>
                                    </select>
                                    <label>Username :</label>
                                    <input class="input focused" name="username" id="focusedInput" type="text" placeholder = "Username" required>
                                    <label>Password :</label>
                                    <input class="input focused" name="password" id="focusedInput" type="password" placeholder = "Password" required>

                                        <?php //if admin = 1 and if user = 2
                                        //$session_id=$_SESSION['id'];

                                        $run = $conn->query("select * from users where user_id = '$session_id'")or die(mysql_error());
                                        $user_row = $run->fetch();
                                        $user_type = $user_row['user_type'];


                                        if ($user_type == 1) {
                                        ?>
                                        <div class="control-group">
                                      <div class="controls">


                                        <button  data-placement="right" title="Click to Save" id="save" name="save" class="btn btn-inverse"><i class="icon-save icon-large"></i> Save</button>
                                                <script type="text/javascript">
                                                $(document).ready(function(){
                                                    $('#save').tooltip('show');
                                                    $('#save').tooltip('hide');
                                                });
                                                </script>
                                      </div>
                                    </div>
                                       <?php //not admin

                                            }   
                                        else { ?>
                                            <button  data-placement="right" title="Click to Save" id="save" name="save" class="btn btn-inverse" disabled="disabled"><i class="icon-save icon-large"></i> Save</button> Only admin allowed!
                                                <script type="text/javascript">
                                                $(document).ready(function(){
                                                    $('#save').tooltip('show');
                                                    $('#save').tooltip('hide');
                                                });
                                                </script>





                                        <?php }


                                    ?>
                            </form>
                            </div>
                        </div>
                    </div>
                    <!-- /block -->
                </div>
    <script>
        jQuery(document).ready(function($){
            $("#add_user").submit(function(e){
                e.preventDefault();
                var _this = $(e.target);
                var formData = $(this).serialize();
                $.ajax({
                    type: "POST",
                    url: "save_user.php",
                    data: formData,
                    success: function(html){
                        $.jGrowl("User Successfully  Added", { header: 'User Added' });
                        window.location = 'admin_user.php';  
                    }
                });
            });
        });
        </script>

save_user.php

<?php
include('dbcon.php');
include('session.php');

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user_type = $_POST['user_type'];
$username = $_POST['username'];
$password = $_POST['password'];


$query = mysql_query("select * from users where username = '$username' and password = '$password' and firstname = '$firstname' and password = '$password'")or die(mysql_error());
                            $row = mysql_fetch_array($query);
                            $username = $row['username'];

    if ($username == 0) {

    {
        $conn->query("insert into users (username,password,firstname,lastname,user_type) values('$username','$password','$firstname','$lastname','$user_type')")or die(mysql_error());
    }
    else
    {
        echo('USERNAME_EXISTS');
    }
    ?>
4
  • $username will never be 0 you might be interested in num_rows.Also mysql is deprecated use PDO Commented Apr 18, 2016 at 11:20
  • just simply use select * from users where username = '$username' and if(count($row) <= 0) Commented Apr 18, 2016 at 11:21
  • you should first apply unique id constraint on that column which contain user_name Commented Apr 18, 2016 at 11:30
  • then mysql never alow duplicate value in column than u can handel the error of duplicate values Commented Apr 18, 2016 at 11:31

3 Answers 3

1

First of all stop using mysql_* extension its deprecated and closed in PHP 7. use mysqli_* or PDO.

Solution:

You can simply check username only in your query like:

SELECT * FROM `users` WHERE `username` = '$username'

And second point is, you just need to use count() or num rows function for checking either record exist or not like:

Example with MYSQLi:

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $db);
$sql = "SELECT * FROM `users` WHERE `username` = '$username'";
$query = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($query);
if(count($row) <= 0){
    //success stuff
}
else{
    // error stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

Far better then my answer!!
@festvender, please select this answer as solution as it is well explained and solves your question.
1

You need to check only username not password.

Uniqueness condition is for username only.

Modify query:

$query = mysql_query("select * from users where username = '$username' and password = '$password' and firstname = '$firstname' and password = '$password'")or die(mysql_error());

To:

$query = mysql_query("select * from users where username = '$username' ")or die(mysql_error());

Note: Don't user mysql_* functions. They are deprecated ones and they will be removed in future PHP versions. Use PDO or mysqli_* instead.

Comments

0

I think you need to display the error message after the submit.So First you need some changes in your jquery

$.ajax({
data: form_data,
url: "save_user.php",
method: "POST",
dataType: "JSON",
beforeSend: function () {
   // show image if process
}
}).done(function (data) {
if (data.status === "success") {
    $.jGrowl(data.message, { header: 'User Added' });
    window.location = 'admin_user.php';
}
if (data.status === "failure") {
    $.jGrowl(data.message, { header: 'Error Found' });
}
}).error(function () {
$.jGrowl("Some Error Found", { header: 'Error' });
}).complete(function () {

});

And in your save_user.php change these lines

$query = mysql_query("select * from users where username = '$username'");
$number = mysql_num_rows($query);
if ($number == 0) {
    $query2=mysql_query("insert into users (username,password,firstname,lastname,user_type) values
    ('$username','$password','$firstname','$lastname','$user_type')");
    if($query2){
        $data['status'] = "success";
        $data['message'] = "User Created successfully.";
    }else{
        $data['status'] = "failure";
        $data['message'] = "Error: " . mysql_error();
    }

}
else
    {
        $data['status'] = "failure";
        $data['message'] = "USERNAME_EXISTS";
    }
echo json_encode($data);

Note: Don't user mysql_* functions. They are deprecated ones and they will be removed in future PHP versions. Use PDO or mysqli_* instead.

3 Comments

The button is not working. I replaced your code with this part $.ajax({ type: "POST", url: "save_user.php", data: formData, success: function(html){ $.jGrowl("User Successfully Added", { header: 'User Added' }); window.location = 'admin_user.php'; } });
The button still not functioning. Please correct if I was wrong, I just replaced your jquery code with this part, others still same $.ajax({ type: "POST", url: "save_user.php", data: formData, success: function(html){ $.jGrowl("User Successfully Added", { header: 'User Added' }); window.location = 'admin_user.php'; } });
great thats better for you i am little busy yesterday sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.