2014-03-04 45 views
0

目前,我有這樣的代碼通過一個查詢的整個結果循環:PHP迭代通過一個MySQL造成了一定的時間

$result = mysqli_query($con, $sql); 
$data = array(); 

while($row = mysqli_fetch_array($result)) { 

    $name  = $row ['name']; 
    $desc  = $row ['description']; 
    $cat  = $row ['category']; 
    $price  = $row ['price']; 
    $quantity = $row ['quantity']; 
    $id  = $row ['productID']; 
    $image  = $row ['image']; 

    $arr = array(); 

    $arr ["id"] = $id; 
    $arr ["name"] = $name; 
    $arr ["desc"] = $desc; 
    $arr ["cat"] = $cat; 
    $arr ["price"] = $price; 
    $arr ["quantity"] = $quantity; 
    $arr ["image"] = $image; 

    array_push($data, $arr); 

} 
echo json_encode($data); 

我想通過一個設定的這一改變能夠環結果。我有一個名爲$amount的代碼,它是我想要的結果數量。

我聽說我應該使用mysql_result()和for循環來計數到$amount,但我不知道我的現有代碼將如何使用該設置!建議請。

編輯:

@Styphon指出了,我實際上並不需要改變我的迭代代碼爲此得到解決。只需要添加一個LIMIT到我的SQL查詢。

+4

爲什麼不只是爲查詢添加限制?爲什麼你把行放入一個var,然後將var放入數組,然後推入數據? – Styphon

+0

我還沒有太多的MySQL經驗,這將如何完成?聽起來它可以工作,但! – benharris

+0

https://dev.mysql.com/doc/refman/5.0/en/select.html尋找LIMIT – Pakspul

回答

2
$sql = "rest of query... 
LIMIT $amount"; //This will limit it to whatever is $amount. Just make sure to have it on the end of your query. 
$result = mysqli_query($con, $sql); 
$data = array(); 

while($row = mysqli_fetch_array($result)) { 

    $arr = array(); 
    $arr["id"] = $row['productID']; 
    $arr["name"] = $row['name']; 
    $arr["desc"] = $row['description']; 
    $arr["cat"] = $row['category']; 
    $arr["price"] = $row['price']; 
    $arr["quantity"] = $row['quantity']; 
    $arr["image"] = $row['image']; 

    array_push($data, $arr); 

} 
echo json_encode($data); 
+0

OP表示存在一個名爲'$ amount'的變量,它反映了待處理結果的數量。所以你想'LIMIT $ amount';作爲你查詢中的最後一行,我相信 – Floris

+1

@Floris謝謝,我錯過了,並且更新了我的答案 – Styphon

0
SELECT * FROM tbl 
LIMIT 0, $amount 

這會限制您的結果爲$金額。

+0

所以'LIMIT 0,$ amount'就在我查詢的最後? – benharris

+0

是的,它應該結束 – Ataman

+0

嗯,這比我想象的要容易得多!謝謝! – benharris

1

無論您使用mysql_還是mysqli_(但應使用mysqli甚至pdo),解決方案都是一樣的。它去的東西沿着這條線:

$num = 0; 
$amount = 10; 

while ($f = mysql_fetch_array($q)) { 
    // your code; 
    $num++; 
    if ($num==$amount) break; 
} 

至於你提到的循環,用for循環你可能會做這樣的事情

for ($i=0;$i<$amount;$i++) { 
    $f = mysql_fetch_array($q); 
    //your code 
} 

很顯然,你應該進行調整以滿足您的需求。

+0

但是很明顯,你應該使用LIMIT,我認爲你知道這個之前 –

+1

你是對的,我已經編輯了答案 –

+0

Upvoting爲「問題的答案」 - 我聽說我需要使用for循環並計數到$ amount_ - 這表示(雖然有一個「while」 )如何完成對未來訪問者有用的信息 - 雖然(正如你指出的),這不是最好的解決方案。 – Floris