使用从while循环检索的数据更新数据库

时间:2014-11-11 12:21:08

标签: php mysql

我有一张名为FRANCE的桌子

  City          Region            LAT   LNG
  PARIS         L'Ile-de-France  
  MARSEILLE     Provenza

现在,我通过使用google api的函数检索LAT和LNG值。要做到这一点,我必须连接城市和地区

所以这就是我的所作所为:

$sql="Select * from France";
$result=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
$city=$row['city'];
$region=$row['region'];

 $address=$city.",".$region.", France";

$coordinates = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' .      urlencode($address) . '&sensor=true');
$coordinates = json_decode($coordinates);

$lat = $coordinates->results[0]->geometry->location->lat;
$lng = $coordinates->results[0]->geometry->location->lng;
 }

现在我想更新表FRANCE以获得此输出

  City          Region            LAT         LNG
  PARIS         L'Ile-de-France   48.856614   2.352222
  MARSEILLE     Provenza          43.296482   5.369780

我该怎么办?

1 个答案:

答案 0 :(得分:1)

这很简单,就像上面的评论一样,你已经获得了结果并提出了请求。收集请求中的响应后,只需发出UPDATE声明。

强制性说明:

  

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

这是一个使用mysqli和准备语句的粗略未经测试的示例。当然,您需要修改这些项目:

// first step connect and make the first query
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = 'SELECT * FROM france';
$query = $db->query($sql);

while($row = $query->fetch_assoc()) {
    // fetch and assign results
    $id = $row['id'];
    $city = $row['city'];
    $region = $row['region'];
    $address = $city.",".$region.", France";

    // make the google request and gather results
    $coordinates = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true');
    $coordinates = json_decode($coordinates);

    // check if there are results
    if($coordinates != null) {
        $lat = $coordinates->results[0]->geometry->location->lat;
        $lng = $coordinates->results[0]->geometry->location->lng;

        // make the update
        $sql2 = 'UPDATE france SET `LAT` = ?, `LNG` = ? WHERE id = ?';
        $update = $db->prepare($sql2);
        // i don't know if this is double column or varchar
        $update->bind_param('ddi', $lat, $lng, $id);
        $update->execute();
    }
}