在表中插入多条记录

问题描述 投票:0回答:2

我目前正在按照官方API源的步骤进行操作。

在项目的当前状态下,我从表中获取信息,更改和插入数据,没有任何错误。

但是我想在我的表中进行批量插入。

这是我的代码:

$array = array();
foreach ($objects as $object) {
    array_push(
        $array,
        "('".$object->lat.",".$object->lng."','".$object->other->lat.",".$object->other->lng."')"
    );
}
$values = implode(",", $array);
$client = new Google_Client();
$tableId = "TableId";
$client->useApplicationDefaultCredentials();
$client->setScopes('https://www.googleapis.com/auth/fusiontables');
$service = new Google_Service_Fusiontables($client);

$service->query->sql("INSERT INTO ".$tableId." ('Location', 'City Location') VALUES ".$values); // I'm sorry, I forgot.

当我尝试在不使用相同代码的情况下输入记录时,它有效

当您有多个记录时,这是我的

sql
变量:

INSERT INTO TableId 
('Location', 'City Location') 
VALUES 
('88.064342,-50.280747','-8.77,-36.62'),
(-55.781345,-69.294770','-28.24,-48.67'),
('14.696452,-26.844802','-19.92,-43.17')

API 返回以下错误:

{  
  "error":{  
    "errors":[  
      {  
        "domain":"fusiontables",
        "reason":"badQueryCouldNotParse",
        "message":"Invalid query: Parse error near ',' (line 1, position 92).",
        "locationType":"parameter",
        "location":"q"
      }
    ],
    "code":400,
    "message":"Invalid query: Parse error near ',' (line 1, position 92)."
  }
}
php google-api-php-client google-fusion-tables
2个回答
1
投票

您无法使用单个 INSERT 语句添加多行 - 您需要为每组值使用一个语句。对于批量插入,您可能希望使用

importRows
而不是 多个 INSERT 语句,因为它通常更快、更可靠,并且消耗的配额也更少。

导入行的 PHP API 文档
如果您选择

importRows
路线,请记下 标准参数,因为您将以这种方式传递新行。相关问题 12


0
投票

我认为这不是谷歌服务问题,而是最终查询字符串的格式问题。您可能缺少引用或缺少括号。

// Flatten the array of objects into values per entry
$location_values = array_map($objects, function($object) {
    [
         $object->lat,
         $object->lng,
         $object->other->lat,
         $object->other->lng,
    ];
}

// $location_values will be a multidimensional array, we need to turn it to a string
$location_values_stringified = array_reduce($location_values, function($final_string, $location) {
    // to turn an array into a string
   $location_string = implode($location, ',');
   // wrap the string in parenthesis
   $location_string = sprintf('(%s)', $location_string);
   return $final_string . ',' . $location_string;
}, '');

// build query string
$query = sprintf("INSERT INTO %s ('Location', 'City Location') VALUES %s", $tableId, $location_values_stringified);

我实际上并没有在 PHP 中执行此操作,因此可能存在一个或 2 个语法错误,但是 应该 可以让您获得所需的格式的相似之处:

INSERT INTO TableId 
('Location', 'City Location') 
VALUES 
('88.064342,-50.280747','-8.77,-36.62'),
(-55.781345,-69.294770','-28.24,-48.67'),
('14.696452,-26.844802','-19.92,-43.17')

如果您需要检查您的

$query
,请在将其发送到
die(var_dump($query));
之前使用
$service
。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.