Thomas Andersson
Thomas Andersson

Reputation: 11

Dynamically binding params Php/Mysqli

Hi I have some problems with merging my array and bind my params.

Error Message = Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in.......

    $headline = $_GET['hl'];
    $county = $_GET['ca'];
    $categories = $_GET['co'];

    $query = 'SELECT COUNT(id) FROM main_table';        

    $queryCond = array(); 
    $stringtype = array();
    $variable = array();


if (!empty($headline)) {
    $queryCond[] = "headline LIKE CONCAT ('%', ? , '%')";
   array_push($stringtype, 's');
   array_push($variable, $headline);
}

if (!empty($county)) {
    $queryCond[] = "county_id = ?";
    array_push($stringtype, 'i');
    array_push($variable, $county);
}

 if (!empty($categories)) {
    $queryCond[] = "categories_id = ?";
    array_push($stringtype, 'i');
    array_push($variable, $categories);
}

if (count($queryCond)) {

    $query .= ' WHERE  ' . implode(' AND ', $queryCond);
}


//var_dump($query);

$stmt = $mysqli->prepare($query);

$variable = array_merge($stringtype, $variable);

print_r($variable);


//var_dump($refs);

    $refs = array();

foreach($variable as $key => $value)


    $refs[$key] = &$variable[$key];


    call_user_func_array(array($stmt, 'bind_param'), $refs);

Upvotes: 1

Views: 518

Answers (2)

Angel M.
Angel M.

Reputation: 2732

It's a bit late answer, but I had issue with dynamically adding values. If you have php v +5.6, you can omit this part

$variable = array_merge($stringtype, $variable);
// and $refs
call_user_func_array(array($stmt, 'bind_param'), $refs);

and using ...token introduced in +5.6v. Here is a fully work example for my case:

// establish mysqli connection
$conn = new mysqli(.....); 
$tableName = 'users';
// Types to bind
$type = 'isss';
$fields = ['id','name', 'email', 'created'];
$values = [1, 'name', '[email protected]', '2018-1-12'];

$sql = "INSERT INTO " . $tableName . " (" . join(',', $fields) . ") VALUES (?,?,?,?)";

$stmt = $conn->prepare($sql);
// Using ...token introduced in php v.5.6 instead of call_user_func_array
// This way references can be omitted, like for each value in array
$stmt->bind_param($type, ...$values);

$stmt->execute();

$stmt->close();

Upvotes: 1

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

You need change this:

$variable = array_merge($stringtype, $variable);

$refs = array();

foreach($variable as $key => $value)
    $refs[$key] = &$variable[$key];

to this:

$variable = array_combine($stringtype, $variable);

Because array_combine() create an array by using one array for keys and another for its values.

Read more at:

http://php.net/manual/en/function.array-combine.php

Upvotes: 1

Related Questions