Reputation: 2984
I have recently began to use OOP in PHP and I am starting with functions which I am fairly familiar with. I have been working on a data-management system connected with MySQL database. I am running into issues when it comes to inserting content into the Database and getting this error:
Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables ... on line 140
This is my code:
public function create_val( $content_array, $table )
{
$array_num = count($content_array);
// create value holders
$value_param = str_repeat( '?, ', $array_num );
$stmt_values = rtrim($value_param, ', ');
// create bind params
$stmt_param = str_repeat('s', $array_num);
foreach($content_array as $key => $value)
{
$key_val[] = $key;
$val[] = $value;
}
$table_rows = implode(', ', $key_val);
$insert_val = implode(', ', $val);
$sql = "INSERT " . $table . " (" . $table_rows . ") VALUES (" . $stmt_values . ")";
if($stmt = $this->_connection->prepare( $sql ))
{
try
{
$stmt->bind_param($stmt_param, $insert_val);
$stmt->execute();
$stmt->close();
}
catch(Exception $e)
{
echo "There was an unexpected problem. " . $e->getMessages();
}
}
}
I know that the error is being caused by this line: $stmt->bind_param($stmt_param, $insert_val);
.
But I just do not understand why; I have checked both the $stmt_param
and $insert_val
and they match in number - in this specific attempt which I am running.
The values are being inserted as a $key => $value
pairs. This is my setup to call the class:
$array = array(
'column1' => 'an item',
'column2' => 'a second content',
'column3' => 'some information',
'column4' => 'what what what???'
);
$db->create_val($array, 'table_name');
My goal with this function is to be as reusable and modular as I possibly can code it. I have looked at many similar questions but have not found any I can use. Even when it came to classes, they were not really reusable for different purposes, and my purpose is to be reusable.
Upvotes: 2
Views: 100
Reputation: 57121
As of PHP 5.6 you can call the bind_param
function with the unpacking operator, which allows you to call it directly (and without using call_user_func_array
), just change this line...
$stmt->bind_param($stmt_param, ...$val);
Upvotes: 3