Roxx
Roxx

Reputation: 3986

Mysqli:mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

I am creating dynamic mysqli query with the help of @chris85. I am able to created this.

<?php
require_once 'include/db.php';    
$firstname = 'Alpha';
$lastname = 'Romeo';

$query = "SELECT * FROM users";

$cond = array();
$params = array();

if (!empty($firstname)) {
    $cond[] = "fname = ?";
    $params[] = $firstname;
}

if (!empty($lastname)) {
    $cond[] = "lname = ?";
    $params[] = $lastname;
}

if (count($cond)) {
    $query .= ' WHERE ' . implode(' AND ', $cond);
}
echo $query;
$stmt = $mysqli->prepare($query);
if(!empty($params)) {
     foreach($params as $param) {
         $stmt->bind_param("s", $param);
        echo $param;
     }
}
$stmt->execute();

?>

When i execute this i got this.

SELECT * FROM users WHERE fname = ? AND lname = ?
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /home/u983213557/public_html/test.php on line 32
AlphaRomeo

I am not sure why it is failing. please advise me to fix this issue.

Upvotes: 0

Views: 746

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

It is failing because mysqli is not PDO and you cannot bind in a loop. Thus you have to use tricks to bind an array in mysqli. Luckily, if your PHP version is 5.6 or 7, you can use this code:

$stmt = $db->prepare($query);
$types = str_repeat('s', count($param));
$statement->bind_param($types, ...$param);
$statement->execute();

if not, then you are bound to use call_user_func()-based solution

Upvotes: 2

Related Questions