我试图通过PDO将数据插入数据库
这是我的代码:
try {
$count = count($db_data);
for ($i=0; $i < $count ; $i++) {
$query_string = "INSERT INTO data (" . $fields[$i] . ") VALUES(" . $values[$i] . ")";
echo $query_string;
$vle = $dbh->prepare($query_string);
$vle->bindValue(':USER', $db_data[$i]['user']);
$vle->bindValue(':SERVER_NAME', $db_data[$i]['server_name']);
$vle->bindValue(':SERVER_NAME', $db_data[$i]['description']);
$vle->bindValue(':PATH', $db_data[$i]['path']);
$vle->bindValue(':DATE', $db_data[$i]['date']);
$vle->execute();
echo "KEY: " . $fields[$i] . "</br>" . "VALUES: " . $values[$i] . "</br>";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
但我收到以下错误:
警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:绑定变量数与
中的令牌数不匹配修改
$query_string
是:
INSERT INTO data (user, server_name, description, path, date) VALUES(:jsieclaf, :srvc07.gnotek.com>, :php.nested.base64.526, :a:1:{i:0;s:70:" /home/jsieclaf/public_html/modules/mod_araticl= hess/mod_araticlhess";}, :Mon, 7 Apr 2014 13:48:56 +0300)
$ db_data是:
array (size=5)
'user' => string ':jhjju' (length=9)
'server_name' => string ':sjvbg07.gnotek.com>' (length=20)
'description' => string ':php.nested.bade454.526' (length=22)
'path' => string ':a:1:{i:0;s:70:" /home/jhjju/public_html/modules/mod_araticl= hess/mod_ereticlhess";}' (length=89)
'date' => string ':Mon, 7 Apr 2014 13:48:56 +0300' (length=31)
答案 0 :(得分:1)
$sql = "INSERT INTO $tableName (" . implode(',', array_keys($assoc_array)) . ") VALUES (" . trim(str_repeat('?,', count($assoc_array)), ',') . ")";
$stm = $dbh->prepare($sql);
$stm->execute(array_values($assoc_array));
答案 1 :(得分:-1)
try { $sql = "INSERT INTO $tableName (" . implode(',', array_keys($assoc_array)) . ") VALUES (" . trim(str_repeat('?,', count($assoc_array)), ',') . ")"; $stm = $db->prepare($sql); $stm->execute(array_values($assoc_array)); } catch (PDOException $e) { echo $e->getMessage(); }