错误:将INSERT内容插入到MySQL数据库中
问题描述:
我最近开始在PHP中使用OOP,并开始使用我非常熟悉的函数。我一直在研究与MySQL数据库连接的数据管理系统。我遇到的问题,当涉及到将内容插入数据库,并收到此错误:错误:将INSERT内容插入到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的,你可以调用bind_param
功能与unpacking operator,它允许你直接调用它(和不使用call_user_func_array
),只是改变这一行...
$stmt->bind_param($stmt_param, ...$val);
1.检查表列和2.与您正在发送的内容进行比较3.echo $ sql查询和4.try在数据库中执行5.tell出现什么错误。 –
@AbdulWaheed我的测试数据库有4列,所有'varchar(500)'我不确定查询与实际冲突有多大关系。 – Samuel
'bind_param'只适用于一次绑定单个参数。 – Scuzzy