我使用PHP&PDO将API的结果插入mysql数据库(innodb)。下面是我的代码:
$insertbrewery = $db->prepare('insert into breweries values(DEFAULT, :api_id, :name, :city, :state, DEFAULT)');
foreach ($data as $result) {
$insertbrewery->bindParam('api_id', $id);
$insertbrewery->bindParam('name', $result[brewery][name]);
$insertbrewery->bindParam('city', $result[brewery][locality]);
$insertbrewery->bindParam('state', $result[brewery][region]);
$insertbrewery->execute();
if ($insertbrewery) {
echo $insertbrewery->rowcount()." breweries successfully submitted.<br />";
} else {
echo "An error occurred with submitting the post to the database. Sorry.";
}
}
最佳答案
参数名为:name
、:city
和:state
(包括前导冒号)。另外,一定要引用数组中的键。
更改此:
$insertbrewery->bindParam('name', $result[brewery][name]);
$insertbrewery->bindParam('city', $result[brewery][locality]);
$insertbrewery->bindParam('state', $result[brewery][region]);
对此:
$insertbrewery->bindParam(':name', $result['brewery']['name']);
$insertbrewery->bindParam(':city', $result['brewery']['locality']);
$insertbrewery->bindParam(':state', $result['brewery']['region']);