我有一个脚本,可以解析 HTML 表中的数据并将其放入数组中。以下是脚本的示例输出:
Array
(
[] => Array
(
[] => Array
(
[] => Array
(
[] => Array
(
[] => 1
)
)
)
)
[Precinct Code] => Array
(
[Precinct] => Array
(
[Total Registered] => Array
(
[Total Voting] => Array
(
[Percent Voting] => 1
)
)
)
)
[004] => Array
(
[AWENDAW] => Array
(
[1299] => Array
(
[926] => Array
(
[71.285] => 1
)
)
)
)
)
我想将这些数组插入 MySQL 数据库,我使用以下代码:
$html = file_get_html('URL GOES HERE');
foreach($html->find('tr') as $row) {
$precinct = $row->find('td',0)->plaintext;
$precinctCode = $row->find('td',1)->plaintext;
$totalRegistered = $row->find('td',2)->plaintext;
$totalVoting = $row->find('td',3)->plaintext;
$percentVoting = $row->find('td',4)->plaintext;
$table[$precinctCode][$precinct][$totalRegistered][$totalVoting][$percentVoting] = true;
/* Dump each array into MySQL table */
$db = new PDO('mysql:host=localhost;dbname=MY_DATABASE_NAME', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $db->prepare(
'INSERT INTO rsltStats (precinctCode , precinct, totalRegistered,
totalVoting, percentVoting ) VALUES (?, ?, ?, ?, ?)');
foreach($table as $values) {
$insert->execute($values);
}
}
但是,它不断抛出错误: fatal error :未捕获的异常“PDOException”,消息为“SQLSTATE[HY093]:无效的参数编号:绑定(bind)变量的数量与 token 的数量不匹配”
我对此还很陌生,因此非常感谢您的帮助。
最佳答案
不要这样做:
$table[$precinctCode][$precinct][$totalRegistered][$totalVoting][$percentVoting] = true;
...
foreach($table as $values) {
$insert->execute($values);
}
这是在 $table 上循环,该表只有一行索引为 precinctCode,然后 $values 最终只有 4 个元素。不是 5。
尝试简单地这样:
$values = array($precinctCode,$precinct,$totalRegistered,$totalVoting,$percentVoting);
...
$insert->execute($values);
如果您之后需要 $table 数组,您仍然可以像现在一样构建 $table[][][] 嵌套数组,但不要使用它来执行 sql。
关于php - 将解析数据中的数组插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058876/