如何用PHP检查MySQL中是否已经存在用户

时间:2013-07-04 08:29:53

标签: php mysql

我正在使用以下不适合我的代码。

$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT COUNT(*) FROM persons WHERE Email = '$_POST[eMailTxt]'";
if (mysqli_query($con,$check)>=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/>";
    }
}
  

类mysqli_result的对象无法转换为int in   的 C:\ XAMPP \ htdocs中\精通\的welcome.php

4 个答案:

答案 0 :(得分:6)

此代码适用于您...

$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/>";
    }
}

答案 1 :(得分:3)

mysqli_query函数返回结果集句柄。然后,您需要从中读取行:

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

另请注意,SELECT count(1) FROM ...将比SELECT count(*) FROM ...更快您在小表中看不到多少差异,但是对于数十万行的大表,差异可能很大

答案 2 :(得分:2)

mysqli_query会返回mysqli_result个对象。不要将此与整数进行比较,请尝试使用num_rows

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

修改:上面假设查询使用SELECT *,这不适用于SELECT COUNT(*)。 Checkout Aleks G的答案。

答案 3 :(得分:0)

您可以尝试以下代码:

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