0

I have written this code , its working to add users but for duplicate user it again saved the value os same user name. i wanted to give popup message if username already taken. i m beginner please help.

  <?php
 ob_start();
  include("db.php");
  if(isset($_POST['send'])!="") {
  $username = mysqli_real_escape_string($con, $_POST['username']);
  $usermail = mysqli_real_escape_string($con, $_POST['usermail']);
  $usermobile = mysqli_real_escape_string($con, $_POST['usermobile']);
  $bool = true;
  $con = mysqli_connect("localhost","root","","demo");
  $result = mysqli_query("SELECT `username` FROM `sample` WHERE username = '$username'");
  if(mysqli_num_rows($result)>0)
  {
          Print '<script>alert("Username has been taken!");</script>'; 

      }
        if ($bool) {
        $inssql = "insert into sample set 
        username = '" . $username . "',
        emailid = '" . $usermail . "',
        mobileno = '" . $usermobile . "',
        created = now()";
        $update = mysqli_query($con, $inssql);


        }
    }
  • If the username is supposed to be unique, you should set a unique index on that column in the database. And your `SELECT` query should only look for the row with that username, not all rows. – jeroen Dec 14 '16 at 14:29
  • Before you are inserting the data into the database check existence of user if count is greater than 0 show the error message else insert the user – Soniya Basireddy Dec 14 '16 at 14:31
  • 2
    Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Dec 14 '16 at 14:32
  • Note - Never select `*` from a table unless for *debug* purposes. If you have 1000's of users, this query will not only run slow but shouldn't need `*` information. – Jaquarh Dec 14 '16 at 14:33
  • I have updated code , still not working – Sajid Mehmood Dec 14 '16 at 14:58

1 Answers1

1

Make sure you finish the script or turn off your flag before making the insert:

if(mysqli_num_rows($result)>0)
{
    Print '<script>alert("Username has been taken!");</script>';
    die('username already taken');
    //$bool = FALSE;
}

If you still having duplicate entries, debug what is the result of $username and compare it with the value in the database.

Jmunoz Dev
  • 461
  • 5
  • 10