Check if username exists in the database

pretty stuck on trying to prevent a user from registering if the username exists. Here is my code:

include('../connection.php');
//get all the names and values that have been posted.
    $username = $_POST['username'];   
    //check if username exists
    $sql = "SELECT * FROM tbl_Freelancers WHERE User_Username = '".$username."'";
    $result = mysqli_query($con,$query);
    if(mysql_num_rows($result)>=1)
       {
        echo"name already exists";
       }
     else
        {  // excecute insert query 

      

I tried a lot of other things to make it work, but for some reason I don't like my code ......

+3


source to share


6 answers


change mysql_num_rows

tomysqli_num_rows

if(mysqli_num_rows($result)>=1)//You are mixing the mysql and mysqli, change this line of code
           {
            echo"name already exists";
           }
         else
            {  //

      



use the binding parameter or try to avoid the value before using it in the request.

+4


source


change..

$sql = "SELECT * FROM tbl_Freelancers WHERE User_Username = '".$username."'";
    $result = mysqli_query($con,$query);

      

to

$sql = "SELECT * FROM tbl_Freelancers WHERE User_Username = '".$username."'";
    $result = mysqli_query($con,$sql);

      



you specified the query in $ sql and executed in $ query ... also get input as ..

 $username = mysqli_real_escape_string($con, $_POST['username']);   

      

for security reasons ...

+2


source


change your query to:

 $sql= "SELECT * FROM tbl_Freelancers WHERE User_Username = '$username'";

$result=mysql_query($sql);

if(mysql_num_rows($result)!=0)
       {
        echo"name already exists";
       }
     else
        {  
        // excecute insert query 
        }

      

0


source


mysql_num_rows

deprecated from PHP 5.5.0

and will be removed in the future

So use the alternative mysqli_num_rows

0


source


try this

include('../connection.php');
 $username = $_POST['username'];   
  $sql = "SELECT * FROM tbl_Freelancers WHERE User_Username = '".$username."'";
    $result = mysql_query($sql);
    if(mysql_num_rows($result)!=0)
       {
        echo"name already exists";
       }
     else
        {
        echo ".........";
}   

      

0


source


the variable $query

should be the second argument to mysqli_query, you used instead $sql

. so replace $sql

with $ query in mysqli_query()

and use mysqli

insteadmysql_num_rows()

-1


source







All Articles