2016-02-24 38 views
1

我有以下工作代碼查詢外while循環,使用循環的內部,一點兒也不工作

$notchDetails = mysqli_query($conn, "SELECT * FROM notches WHERE projectid = ".$projectid." LIMIT ".$offset.", ".$limit.""); 
// i want $query here // 
$outp3 = "["; 
if (mysqli_num_rows($notchDetails) > 0) { 
    while($notch = mysqli_fetch_assoc($notchDetails)) { 

    $query = mysqli_query($conn, "DESCRIBE $table"); 

    $count = count($notch); 
    $allnotches[] = $notch["notchid"]; // $allnotches is needed further in script // 
    if ($outp3 != "[") {$outp3 .= ",";} 

    $outp3 .= "{"; 

    $x = 1; 
    while ($rs = mysqli_fetch_assoc($query)) { 
     $field = $rs["Field"]; 
     $outp3 .= '"'.$field.'":"'.$notch[$field].'"'; 
     if ($x != $count) { $outp3 .= ","; } 
     $x++; 
    } 

    $outp3 .= "}"; 
    } 
} 
$outp3 .="]"; 

(不要看的變數名稱缺口,could'nt找到更好的翻譯比缺口它的複雜;-))

問題解釋說:

當我把$query = mysqli_query...

while循環(略低於$notchDetails = mysqli_query...)外,

只得到1分的結果,其餘的在空:while ($rs = mysqli_fetch_assoc($query)) { //result// }

房顫據我所看到的,它應該與$查詢工作在循環之上。但我不明白爲什麼它不是。

有人可以解釋爲什麼這不起作用嗎?

P.s.將其置於循環之外的原因是性能/速度

+0

我是否正確地創建了JSON結構? –

+0

沒錯。我需要將多個JSON放入1個文本文檔(使用序列化,然後對其進行加密)。你有更好的解決方案嗎? –

+0

是的。 json_encode() –

回答

1

mysqli_fetch_assoc正在迭代通過mysqli_result。當您結束迭代時,您無法再次迭代它。您可以創建一個新的查詢並對其進行迭代。

所以,當你把$query = mysqli_query($conn, "DESCRIBE $table");while循環之外,你是不是創建一個新的查詢迭代,因此,第一迭代完成後,mysqli_fetch_assoc是不是因爲你沒有新的查詢返回任何東西,和舊的查詢已經是迭代。

我會做這樣的事情:

$fields = []; 

$table_structure = mysqli_query($conn, "DESCRIBE `notches`"); 
while ($row = $table_structure->fetch_assoc()) { 
    $fields[] = $row['Field']; 
} 

$notch_details = mysqli_prepare(
    $conn, 
    'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?' 
); 
$notch_details->bind_param('iii', $projectid, $offset, $limit); 
$notch_details->execute(); 
$notch_details = $notch_details->get_result(); 

$result = []; 

while($notch = $notch_details->fetch_assoc()) { 
    $values = []; 

    foreach ($fields as $field) { 
     $values[$field] = $notch[$field]; 
    } 

    $result[] = $values; 
} 

$result = json_encode($result); 

正如你所看到的,我已經準備了$fields列表一次,我用它之後,就像字段列表,無需再次查詢表的說明然後再次。

編輯:此外,當您查詢數據庫並獲取數據作爲一個關聯數組,你不需要對錶領域的知識,因爲你已經在你的結果字段名稱:

$notch_details = mysqli_prepare(
    $conn, 
    'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?' 
); 
$notch_details->bind_param('iii', $projectid, $offset, $limit); 
$notch_details->execute(); 
$notch_details = $notch_details->get_result(); 

$result = json_encode($notch_details->fetch_all(MYSQLI_ASSOC)); 

您將有這裏沒有查詢表結構的相同結果。

+0

謝謝。很好的解釋! –

+0

@RamonBakker。不用謝。我也希望這個答案不僅可以作爲你的問題的答案,而且還可以作爲準備好的語句的一個例子,它比直接將變量插入查詢更安全。 –

+0

我知道SQL注入,我知道如何防止它。 –