【发布时间】:2019-09-22 20:09:57
【问题描述】:
通过 PDO 将数组插入使用 PHP 的 MySQL 数据库对我不起作用。它说“无效的参数号”,即使数组有 41 个值; PDO 命名 41 列;并且准备好的查询有 41 个问号。
该数组有 41 个值(我用 var_dump 检查过),如下所示:
$data = [
'countrycode' => $_GET["id"],
'country' => $_GET["country"],
'region' => $_GET["region"],
'law_db_region' => $_GET["law_db_region"],
[... etc ...]
]
我的 PDO 代码如下(是的,这些是 41 列和 41 个问号):
$sql = "INSERT INTO awards_country
(countrycode, country, region, law_db_region, law_db_national,
law_db_national2, const_url, const_version, const_date, const_dummy,
const_article, const_wording, const_article2, const_wording2, const_article3,
const_wording3, law_dummy, law_act, law_article, law_source,
law_date, law_act2, law_article2, law_source2, law_date2,
law_act3, law_article3, law_source3, law_date3, web_dummy,
web_url, web_organ, web_language, web_date, web_url2,
web_organ2, web_language2, web_date2, wikipedia_url, wikipedia_date,
comment)
VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($sql);
$stmt->execute($data);
我得到的错误仍然是:
致命错误:未捕获的 PDOException:SQLSTATE[HY093]:无效参数 number:参数未在 [...]country-insert.php:99
中定义堆栈跟踪:#0 [...]country-insert.php(99): PDOStatement->execute(Array) #1 {main} 抛出 /data/web/e96483/html/awards/country-insert.php 第 99 行
【问题讨论】:
-
我已经测试了很长时间,但这可能是由于您的
$data数组具有关联键,而您在语句中使用了位置?。这可能很容易用$stmt->execute(array_values($data))解决,用数字键替换关联数组键。或者可以通过首先创建一个普通数组来解决$data = [$_GET['id'], $_GET['country'],....] -
print_r( $data );在 PDO 执行之前确保它包含您需要的所有字段。 -
我知道这是在你修复它之后,但如果你使用 PDO 坚持关联数组并将查询中的
?更改为命名参数 -:countrycode等等。这意味着更容易确保将正确的值放入正确的字段中,如果在错误的位置添加 1 个字段,则仅 41 个字段的数组很容易错位。