循环后bind_param数组php更新表

时间:2014-11-11 16:41:17

标签: php sql-update bind

我有这段代码

$sql="INSERT INTO cerca_strutture (id, struttura, indirizzo, lat, lng, distanza)
SELECT id, struttura, indirizzo, lat, lng, P1AP_NOME 
FROM lista";
$query = $db->query($sql);


$lat1="39.3048001";
$lng1="16.2523086";

$sql= "SELECT * FROM cerca_strutture";
$query = $db->query($sql);
while($row = $query->fetch_assoc()) {
$id=$row['id'];
$lat_struttura=$row['lat'];
$lng_struttura=$row['lng'];

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$lat1,$lng1&destinations=$lat_struttura,$lng_struttura&mode=driving&language=it-IT&sensor=false";
$data = @file_get_contents($url); 
$result = json_decode($data, true);


foreach($result['rows'] as $distance) {
$distanza=$distance['elements'][0]['distance']['text'];
}

我想用这个新值更新表cerca_strutture $ distanza

所以我在这段代码中做了

 $sql2 = 'UPDATE lista SET `distanza` = ? WHERE id = ?';
 $update = $db->prepare($sql2);
  $update->bind_param('di', $distance, $id);
 $update->execute();

但结果是

Fatal error: Call to a member function bind_param() on a non-object in ....

2 个答案:

答案 0 :(得分:0)

我需要问几个问题,以便在您正在执行的代码中提供正确的答案,

foreach($result['rows'] as $distance) {
$distanza=$distance['elements'][0]['distance']['text'];
}

你想在那里实现什么?

答案 1 :(得分:0)

鉴于您说要更新表,请使用表cerca_strutture。您需要像这样编写代码

$sql2 = 'UPDATE table cerca_strutture SET distanza = :diz WHERE id = :id';
$update = $db->prepare($sql2);

//bind the two parameters separately for better readablity
$update->bind_Param(':diz', $distance);
$update->bind_Param(':id', $id);

$update->execute();