Agung
Agung

Reputation: 13803

error on bind_param , number of parameters in prepared statement doesn't match

I know there are some questions about this, I have tried, but none of those solved my problem. so here is my problem.

I am trying to get a user's data, there are 2 parameters needed, if both of parameters are available, the code run seamlessly, but if $word parameter is not available, then I have got this warning + correct result

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php on line 379

{"users":[{"id":53,"username":"paulpogba","email":"[email protected]","avatar":"","fullname":"paul pogba"},{"id":56,"username":"waynerooney","email":"[email protected]","avatar":"","fullname":"wayne rooney"}]}

the JSON result is good as i expect. but i want to omit the warning message. the problem is on the $statement-> bind_param('ss',$words,$words); i believe there are only 2 ? in the SQL syntax.

I don't know why it is said Number of variables doesn't match number of parameters in prepared statement, I can't see what went wrong in here :(

 function searchUsers ($currentUser,$words) {


        $query = "SELECT id,username,email,avatar,fullname FROM users WHERE NOT username= '$currentUser'";

        if (!empty($words))  {
            $query .= "AND (username LIKE ? OR fullname LIKE ?)";
        }


        $statement = $this->conn->prepare($query);

        if (!$statement) {
            throw new Exception($statement->error);
        }



        if (!empty($words)) {
            $words = "%".$words."%";
        }



        $statement-> bind_param('ss',$words,$words);
        $statement ->execute();

        // result we got in execution
        $result = $statement->get_result();

        // each time append to $returnArray new row one by one when it is found
        while ($row = $result->fetch_assoc()) {
            $returnArray[] = $row;
        }

        return $returnArray;


    }

Upvotes: 0

Views: 120

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76426

Instead of

$statement-> bind_param('ss',$words,$words);

you need

if ($words) {
    $statement-> bind_param('ss',$words,$words);
}

Explanation: You need to add those parameters if and only if $words is truey.

Upvotes: 3

Related Questions