[英]Mysql - select several rows with same value
我有一個名為“數據”的表,以及一些列:
用戶,單位,價格,折扣,說明。
----- ----- ------ --------- -----------
| user | unit | price | discount | description |
----- ----- ------ --------- -----------
| test | unit | 100 | 50 | des |
----- ----- ------- -------- -----------
| test2| unit2 | 200 | 20 | des |
----- ----- ----- -------- -----------
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM data WHERE description='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"user"=>$res['user'],
"unit"=>$res['unit'],
"price"=>$res['price'],
"discount"=>$res['discount']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
從這段代碼中,我得到:
{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
所以它只是第一行。 我想讓他們兩個像這樣:
{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
{"result2":[{"user":"test2","unit":"unit2","price":"200","discount":"20"}]}
所以會有2個數組
您將需要編寫一個包含mysqli_fetch_assoc()
調用的循環。 進行迭代時,存儲數據行。
while($row = mysqli_fetch_assoc($r)){
array_push($result, array(
"user" => $row['user'],
"unit" => $row['unit'],
"price" => $row['price'],
"discount" => $row['discount']
)
);
}
或者,如果在SELECT
子句中替換*
以指定所需的行,則可以在mysqli_fetch_assoc()
手冊頁上使用投票最多的注釋...
for ($result = []; $row = mysqli_fetch_assoc($r); $result[] = $row);
這種緊湊的單行代碼可將您的結果集轉換為具有與先前代碼塊相同結構的多維數組,而無需迭代array_push()
函數調用。
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM data WHERE description='".$id."'";
$r = mysqli_query($con,$sql);
$result = array();
while ($res = mysqli_fetch_assoc($r)){
$aRaw["user"] = $res['user'];
$aRaw["unit"] = $res['unit'];
$aRaw["price"] = $res['price'];
$aRaw["discount"] = $res['discount'];
$result[] = $aRaw;
}
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
警告 :代碼容易受到SQL注入攻擊
首先,您的查詢對SQL注入開放,您應該使用mysqli preprared語句
所以你的代碼看起來像這樣
編輯:我的原始答案不完整,因為我沒有在下面進行測試,這是我的更正答案
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM data WHERE description=?";
$stmt = mysqli_prepare($con,$sql);
$stmt->bind_param("s", $id);
$stmt->execute(); //originally I combined this and next line, it was incorrect
if ($result = $stmt->get_result()){
//originally I used wrong method below
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
//uncomment below if you're sending response as json responese
//header('Content-Type: application/json');
echo json_encode($myArray);
}
$result->close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.