检查数据库中是否存在用户名

时间:2014-10-14 09:45:02

标签: php mysql mysqli

如果用户名存在,

试图阻止用户注册。这是我的代码:

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 

我已尝试过很多其他东西让它工作但由于某些原因我的代码不喜欢我......

6 个答案:

答案 0 :(得分:4)

mysql_num_rows更改为mysqli_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
            {  //

使用bind param或proplerly转义你的值,然后在查询中使用它。

答案 1 :(得分:2)

变化..

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

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

您在$ sql中指定了查询并在$ query中执行... 也可以输入..

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

出于安全原因......

答案 2 :(得分:0)

将您的查询更改为:

 $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 
        }

答案 3 :(得分:0)

mysql_num_rowsPHP 5.5.0起已弃用,将来会被删除

因此请使用替代mysqli_num_rows

答案 4 :(得分:0)

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 ".........";
}   

答案 5 :(得分:-1)

你的$query变量必须是mysqli_query中的第二个参数,而不是$sql。所以在$sql函数中使用$ query替换mysqli_query()并使用mysqli代替mysql_num_rows()