我最近开始在 PHP 中使用 OOP,并且从我相当熟悉的函数开始。我一直在研究一个与MySQL数据库连接的数据管理系统。当我将内容插入数据库并收到此错误时,我遇到了问题:
Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables ... on line 140
这是我的代码:
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();
}
}
}
我知道错误是由这一行引起的:$stmt->bind_param($stmt_param, $insert_val);
。
但我就是不明白为什么;我已经检查了 $stmt_param
和 $insert_val
并且它们在数量上匹配 - 在我正在运行的这个特定尝试中。
这些值将作为 $key => $value
对插入。这是我调用该类的设置:
$array = array(
'column1' => 'an item',
'column2' => 'a second content',
'column3' => 'some information',
'column4' => 'what what what???'
);
$db->create_val($array, 'table_name');
我对这个函数的目标是尽可能地实现可重用和模块化。我看过很多类似的问题,但没有找到任何我可以使用的问题。即使涉及到类,它们也不能真正用于不同目的的可重用,而我的目的就是可重用。
最佳答案
从 PHP 5.6 开始,您可以使用 unpacking operator 调用 bind_param
函数。 ,它允许您直接调用它(并且不使用 call_user_func_array
),只需更改此行...
$stmt->bind_param($stmt_param, ...$val);
关于php - 错误: class to INSERT content into MySQL database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901891/