Cal37
Cal37

Reputation: 98

Getting "wrong parameter count..." error with prepared statement

I have been trying to learn prepared statements so that we can start implementing them thoughout our PHP sites. This function takes values (or none) from text boxes on a search form using the $_POST transfer method then uses the names and values of those textboxes to add criteria to the WHERE clause. The function worked previously ut I can't seem to get the prepared statement to function.

Researching several scripts I started using the one below and worked out a few bugs. now when I run it I get the error Wrong parameter count for mysqli_stmt::bind_param()

After this query runs I want to export the values into a table and was working before attempting the prepared statement.

Here is the code I have so far:

  <?php

   $db = mysqli_connec("ip_address", "loginname", "password", "database");

    $refs = array('sssss');

    foreach ($_POST as $key => $value)
     {
       $refs[] =& $_POST[$key];
      }    

$query = "SELECT col1, col2, col3, col4, col5 FROM tbl_name WHERE 1=1";
    foreach ($_POST as $k => $v) 
    { 
      if(!empty($v)) {
        $query .= " AND $k = ?"; 
        $params[$k] = $v;
        }   
    }       

    $results = $db->prepare($query);        

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

    $results->execute();    

?>

Upvotes: 1

Views: 4529

Answers (2)

Cal37
Cal37

Reputation: 98

Ok, the way I solved this was to scrap everything and start over, which is always fun...but the new script that works for what I need is here

<?php


$dbhost     = "ip_address";
$dbname     = "db_name";
$dbuser     = "db_login";
$dbpass     = "db_pass"; 

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

    $query = "SELECT * FROM tbl_name WHERE 1=1";

    foreach ($_POST as $k => $v) 
    { 
      if(!empty($v)) {
        $query .= " AND $k LIKE ?";
        $params[] = $v;     
      }  
    }   

    $results = $conn->prepare($query);  
    $results->execute($params);

    $results->bindColumn(1, $no);
    $results->bindColumn(2, $date);
    $results->bindColumn(3, $name);
    $results->bindColumn(4, $id);
    $results->bindColumn(5, $path);

?>

Upvotes: 0

Michael
Michael

Reputation: 12806

Parameters passed to mysqli_stmt::bind_param must be passed by reference, and only variables can be passed by reference, so you cannot pass the result of a function directly into call_user_func_array in this case. Also, the first parameter passed to bind_param is a string list of the variable types. Instead, try this:

// Change to whatever types are relevant
$refs = array('sss');

foreach ($arr as $key => $value)
{
  $refs[] =& $arr[$key];
}

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

Edit

This line is wrong:

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

Should be

$results = $db->prepare($query);

Upvotes: 3

Related Questions