我一直无法找到此错误的原因。我知道这通常是由于执行()函数期间参数和值的数量不匹配引起的。但是,我已经使用 var_dump 和 echo 反复验证我的参数和值在此过程的每个阶段在数量上是否匹配。有人可以告诉我我的代码哪里错了吗?谢谢!
首先,这是我的初始代码:
$insert = array(
array(
'fName' => 'Bob',
'mName' => 'C',
'lName' => 'Smith',
'suffix' => 'Jr'
),
array(
'fName' => 'Tim',
'mName' => 'K',
'lName' => 'Jones',
'suffix' => 'Sr'
),
array(
'fName' => 'Jim',
'mName' => 'P',
'lName' => 'Hampton',
'suffix' => 'III'
)
);
$db = new Connect('clients');
$db->insertMultiple($insert);
然后,这是我的相关类函数:
public function insertMultiple($array)
{
foreach($array as $inner)
{
$fields = '(';
$values = '(';
foreach ($inner as $key => $value)
{
$fields .= $key . ',';
$values .= ':' . $value . ',';
}
if (substr($fields, -1, 1) == ',')
{
$fields = substr($fields, 0, -1);
}
if (substr($values, -1, 1) == ',')
{
$values = substr($values, 0, -1);
}
$fields .= ')';
$values .= ')';
$sql = "INSERT INTO $this->name $fields VALUES $values";
$this->query($sql);
$this->bindValues($inner);
try
{
$this->execute();
}
catch(PDOException $e)
{
$date = new DateTime();
file_put_contents($this->file, trim($this->error = $e->getMessage()). ' ' . $date->format('Y-m-d H:i:s') . PHP_EOL,FILE_APPEND);
}
}
}
这个调用的函数是:
public function bindValues($array)
{
foreach($array as $param => $value)
{
$param = ':' . $param;
$this->bind($param,$value);
}
}
和
public function bind($param, $value, $type = null)
{
if (is_null($type))
{
switch (true)
{
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
我的查询方法:
public function query($query)
{
$this->stmt = $this->dbh->prepare($query);
}
有人请指出我哪里出错了!谢谢!