mysqli结果来自更新查询中使用的select查询


mysqli results from select query used in update query

一次只能打开一个来自mysqli的结果集,我遇到了问题。特别是,我试图循环通过一个选择查询,并在执行操作后更新该查询中的列。

$db = new mysqli($DBServer, $DBUser, $DBPass , $DBName);
$sql = 'SELECT UPRN, POSTCODE FROM T_TEMP';
$stmt = $db->prepare($sql);
$stmt -> Execute();
<Create an array from the above select statement as i understand that mysqli can 
only hold one result set at once (seems odd). I am unsure how to do this such that
i can then reference UPRN and POSTCODE later>
$stmt->Close();
$sql = 'update T_TEMP set LAT = ?, LONG = ? where UPRN = ?';
$stmt = $db ->prepare($sql);  
<loop through that array built above grabbing UPRN and POSTCODE as you go through>
$postcode = urlencode(<Reference the postcode in the array>);
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false"; 
$xml = simplexml_load_file($request_url);
$lat = round(floatval($xml->result->geometry->location->lat),4);
$long = round(floatval($xml->result->geometry->location->lng),4);
$stmt -> bind_param('ddi',$lat,$long,$UPRN);
$stmt -> Execute();
<end loop>

我正在努力将第一个查询的结果放入一个数组,然后在循环中引用该数组,以便设置值。非常感谢您的帮助!

不要使用mysqli。请改用PDO。在后一种情况下,所需的代码只有一行:

include 'db.php';
$sql  = 'SELECT UPRN, POSTCODE FROM T_TEMP';
$stmt = $db->prepare($sql);
$stmt->execute();
$array = $stmt->fetchAll(); // here you are

在被引导到正确的方向后,我结束了将结果集读取到一个数组中,然后在该数组中循环。(这条评论被否决了,但我正在编辑它,以便其他人更容易找到)。

您不能打开两个mysqli查询,因为服务器只允许您在内存中保存一个查询(实际上是在服务器上)。因此,您将第一个查询读取到php数组中,然后在该数组中循环执行mysqli语句。

$vInteger =1; //This is just an example variable
$sql ='select column from table where column = ?'; //select with a passed value
$stmt = db->prepare($sql);
$stmt-> bind_param('i', $vInteger); //again, this could be a string, double or integer
$stmt->execute();
$result = $stmt->get_result(); //retrieves the results from the server into a class
while ($row = $result->fetch_assoc(){
   $Array[] = $row; //reads the rows into a new array
} 
$stmt -> free_result(); //Drop the mysqli bit cause you are going to need it again! :)
foreach($Array as $item){
  $item['Column']; // this is the column name from your original query

 // Of course in here you might want to do another mysqli query with the prepare etc etc and reference the $item.
 }

如果您决定使用对我有用的mysqli,并且我认为get_result创建了一个mysqli结果类,您可以将fetch_assoc方法应用到该类。。