2013-07-11 66 views
0

我遇到了問題,只能從mysqli一次打開一個結果集。 特別是我試圖通過選擇查詢循環並在執行操作後更新該查詢中的列。從更新查詢中使用的select查詢得到的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> 

我與得到所述第一查詢的結果到一個數組,然後引用該環內的陣列,所以我可以設置的值掙扎。 任何幫助非常感謝!

+0

告訴我們您的陣列?這將有很大的幫助。 – IROEGBU

+0

我沒有陣列,我知道我需要建立一個陣列,但我不確定如何去做。我將編輯代碼,使其更加明顯,我卡住了。 – Culture

回答

1

不要使用mysqli。改爲使用PDO。在後一種情況下該期望代碼將是一個單行的:

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

儘管這個問題與我的回答無關,但我也可以回答這個問題。使用prepare()應該是一種習慣。或者說是一種反射。準備允許您使用總是必須使用的準備好的語句。 –

+0

啊所以我現在有: '$ AddressArray = array(); $ AddressArray = $ stmt-> fetchAll(); foreach($ ArrayAddressSingle as $ AddressArray){ }' 我該如何處理循環內的那些列? – Culture

-1

在正確的方向我結束讀取所述結果集到一個數組,然後通過該數組循環在轉向之後。 (這個評論已被下調,但我正在編輯它以使其他人更容易找到)。

你不能打開兩個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創建到可以應用FETCH_ASSOC方法的mysqli的結果類..