获取错误:类mysqli的对象无法在第5行转换为字符串[重复]

获取错误:类mysqli的对象无法在第5行转换为字符串[重复]

问题描述:

This question is an exact duplicate of:

I'm getting this error:

Catchable fatal error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\gym\userAvailability.php on line 5

And this is the code:

<?php

function username_exists($username, $con){

    $sql = "SELECT * FROM admin WHERE username = '$username'";
    $result = mysqli_query($con, sql);
    $resultarr = mysqli_fetch_assoc($result);


    if(!mysqli_num_rows($result) == 1){
        return true;
    }else{
        return false;
    }
}

I've also checked all the variable name from the .php file that the function username_exist is being used and it is all correct. Any ideas on how to fix this?

</div>

For one, this code is vulnerable to SQL injection - you should use prepared statements with placeholders instead. You're also fetching the result, which isn't used - so you can get rid of the mysqli_fetch_assoc() inside this function.

Your actual issue though, is a dollar-sign missing in front of your $sql and the logic here if(!mysqli_num_rows($result) == 1) { is inverse. If there is a result, you basically get !1 == 1, which is false (as !1 becomes 0, so you get 0 == 1). So the inverse-operator ! had the result be the other way around.

Cleaned a bit, fixed the logical issue and added prepared statements, would look like this

function username_exists($username, $con){
    $stmt = $con->prepare("SELECT * FROM admin WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->store_result();
    $num_rows = $stmt->num_rows;
    $stmt->close();

    return $num_rows == 1 ? true : false;
}

This function would now return true if the username is found in the database. You should now use this function like

if (!username_exists($_POST['username'], $con) {
    /* Do the insert to the database here */
} else {
    /* The username was taken!
       Don't perform the INSERT query */
}

When passing the $username parameter to the function, use the raw username (don't use mysqli_real_escape_string() on it here, since we're using prepared statements).


You might also want to look into adding the UNIQUE constraint for your username-column in the database.