How to check if user already exists in MySQL with PHP

前端 未结 4 1058
失恋的感觉
失恋的感觉 2020-12-10 00:31

I am using following code which is not working for me.

$con=mysqli_connect(\"localhost\",\"root\",\"\",\"my_db\");
$check=\"SELECT COUNT(*) FROM persons WHER         


        
相关标签:
4条回答
  • 2020-12-10 00:44

    You can try the following code:

    $query_code = "SELECT COUNT(itemCode) FROM masterData WHERE itemCode='{$itemCode}'";
    $result_login = mysqli_query($conn,$query_code);
    $anything_found = mysqli_num_rows($result_login);
    
    if($anything_found > 0) {
        $formOk = false;
        echo "ITEM CODE ALREADY EXISTS! Please try again.";  
    }
    
    0 讨论(0)
  • 2020-12-10 00:45

    this code works fine for you...

    $con=mysqli_connect("localhost","root","","my_db");
    $check="SELECT * FROM persons WHERE Email = '$_POST[eMailTxt]'";
    $rs = mysqli_query($con,$check);
    $data = mysqli_fetch_array($rs, MYSQLI_NUM);
    if($data[0] > 1) {
        echo "User Already in Exists<br/>";
    }
    
    else
    {
        $newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
        if (mysqli_query($con,$newUser))
        {
            echo "You are now registered<br/>";
        }
        else
        {
            echo "Error adding user in database<br/>";
        }
    }
    
    0 讨论(0)
  • 2020-12-10 00:59

    mysqli_query returns a mysqli_result object. Rather than comparing this to an integer try using num_rows:

    $res = mysqli_query($con,$check);
    if($res->num_rows){
        //User exists
    }
    

    Edit: The above assumed the query was using SELECT * and this will not work with SELECT COUNT(*). Checkout Aleks G's answer.

    0 讨论(0)
  • 2020-12-10 01:03

    mysqli_query function returns a resultset handle. You then need to read the rows from it:

    $rs = mysqli_query($con,$check);
    $data = mysqli_fetch_array($rs, MYSQLI_NUM);
    if($data[0] > 1) {
        //user exists;
    }
    

    Also note that SELECT count(1) FROM ... will be faster than SELECT count(*) FROM ... You won't see much of a difference in a small table, but with a large table of several hundred thousand rows, the difference may be significant.

    0 讨论(0)
提交回复
热议问题