我有一张名为' data'的表格,以及一些列:
用户,单元,价格,折扣描述。
----- ----- ------ --------- -----------
| 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个阵列。
答案 0 :(得分:1)
您需要编写一个包含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()
函数调用。
答案 1 :(得分:0)
<?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注入攻击
答案 2 :(得分:0)
首先你的查询是对sql注入开放的,你应该使用mysqli preprared statement
那么你的代码看起来就像这样
编辑:我的原始答案不完整,因为我没有在下面测试它是我的更正答案
it("addCategoryWithProducts", function(done){
addCategoryWithProducts(categoryMock)
.then(function(catWithPrds){
expect(catWithPrds).toBeDefined();
expect(catWithPrds.products).toBeDefined();
expect(catWithPrds.products.length).toBe(3);
})
);