我将数组中的对象输入数据库。
我有一个名为$graphObject
我像这样循环遍历数组,
foreach($graphObject['tagged_places']->data as $data) {
}
然后我想获取这些值中的每一个并将其输入mysql DB
PDO
$data->id
$data->created_time
$data->place->id
$data->place->location->latitude
$data->place->location->longitude
$data->place->name
我很困惑如何写这个循环来输入这些字段中的每一个foreach
时间存在一个新字段。
假设数据库连接已打开且数据库中的字段名为
id created_time place_id latitude longitude name
我如何用PDO写这个?
答案 0 :(得分:1)
您可能想要做的是在循环中构建插入,然后只执行一个insert语句。所以像这样:
$sql = <<<EOT
INSERT INTO table (
`id`,
`created_time`,
`place_id`,
`latitude`,
`longitude`,
`name`)
VALUES
EOT;
foreach($graphObject['tagged_places']->data as $data) {
// add values into string you can remove single quotes if not needed
// (i.e. for numeric data types)
$values = <<<EOT
(
'{$data->id}',
'{$data->created_time}',
'{$data->place->id}',
'{$data->place->location->latitude}',
'{$data->place->location->longitude}',
'{$data->place->name}'
),
EOT;
$sql .= $values;
}
$sql = rtrim(',', $sql);
// execute query using $sql
// assume you have properly instantiated PDO object in $pdo
$result = $pdo->query($sql);
if (false === $result) {
// something went wrong, so log an error
// this assumes you have not configured PDO to throw exceptions
error_log(var_export($pdo->errorInfo(), true));
} else {
// continue doing whatever you want to do
}
答案 1 :(得分:1)
创建预备声明:
$stmt = $db->prepare('
INSERT INTO table
(id, created_time, place_id, latitude, longitude, name)
VALUES
(?, ?, ?, ?, ?, ?)
');
在每个循环上执行
foreach($graphObject['tagged_places']->data as $data) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->name
));
}