-1

我正在使用以下对我不起作用的代码。

$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 类的对象无法在 C:\xampp\htdocs\Exp\welcome.php中转换为 int

4

4 回答 4

5

这段代码对你来说很好......

$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/>";
    }
}
于 2013-07-04T08:39:01.197 回答
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 ... 您在小表中看不到太大差异要快,但是对于数十万行的大表,差异可能很大。

于 2013-07-04T08:33:53.743 回答
2

mysqli_query返回一个mysqli_result对象。与其将其与整数进行比较,不如尝试使用num_rows

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

编辑:上面假设查询正在使用SELECT *,这不适用于SELECT COUNT(*). 查看 Aleks G 的答案。

于 2013-07-04T08:32:15.893 回答
-1

您可以尝试以下代码:

$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.";  
}
于 2016-07-30T02:13:47.203 回答