douren9077 2017-04-01 00:34
浏览 76
已采纳

Mysql - 选择具有相同值的多个行

I've got a table called 'data', and some columns:
user,unit,price,discount,description.

 -----   -----  ------  ---------   ----------- 
| 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);
 }

From this code, I get:

{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}

so it's just the first row. I want to get both of them like this:

{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
{"result2":[{"user":"test2","unit":"unit2","price":"200","discount":"20"}]}

so there will be 2 arrays.

  • 写回答

3条回答 默认 最新

  • dousi3362 2017-04-01 00:44
    关注

    You will need to write a loop containing calls of mysqli_fetch_assoc(). As you iterate, store the rows of data.

    while($row = mysqli_fetch_assoc($r)){
        array_push($result, array(
             "user" => $row['user'],
             "unit" => $row['unit'],
             "price" => $row['price'],
             "discount" => $row['discount']
             )
         );
    }
    

    Or if you replace the * in your SELECT clause to nominate your desired rows, you can use the top-voted comment on the mysqli_fetch_assoc() manual page...

    for ($result = []; $row = mysqli_fetch_assoc($r); $result[] = $row);
    

    This compact one-liner will convert your resultset into a multidimensional array with the same structure as the previous code block without the iterated array_push() function calls.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用