【问题标题】:How to select multiple rows from mysql with one query and use them in php如何通过一个查询从mysql中选择多行并在php中使用它们
【发布时间】:2011-09-22 20:00:18
【问题描述】:

我目前有一个如下图所示的数据库。

其中有一个查询选择 number1 等于 1 的行。使用时

mysql_fetch_assoc()

在php中我只得到第一个有没有办法得到第二个?就像通过像

这样的维度数组
array['number2'][2] 

或类似的东西

【问题讨论】:

    标签: php mysql multidimensional-array fetch multirow


    【解决方案1】:

    使用对 mysql_fetch_assoc 的重复调用。它记录在 PHP 手册中。

    http://php.net/manual/function.mysql-fetch-assoc.php

    // While a row of data exists, put that row in $row as an associative array
    // Note: If you're expecting just one row, no need to use a loop
    // Note: If you put extract($row); inside the following loop, you'll
    //       then create $userid, $fullname, and $userstatus
    while ($row = mysql_fetch_assoc($result)) {
        echo $row["userid"];
        echo $row["fullname"];
        echo $row["userstatus"];
    }
    

    如果需要,您可以使用它来构建一个多维数组,以供脚本的其他部分使用。

    【讨论】:

    • 我应该知道它在里面。非常感谢!
    【解决方案2】:
    $Query="select SubCode,SubLongName from subjects where sem=1";
    $Subject=mysqli_query($con,$Query);
    $i=-1;
    
    while($row = mysqli_fetch_array($Subject))
    {
        $i++;
    
        $SubjectCode[$i]['SubCode']=$row['SubCode'];
        $SubjectCode[$i]['SubLongName']=$row['SubLongName'];
    
    }
    

    这里的while循环将获取每一行。该行的所有列将存储在$row变量(数组)中,但是当下一次迭代发生时它会丢失。所以我们复制数组的内容@987654323 @ 到一个名为$SubjectCode的多维数组中。每一行的内容将存储在该数组的第一个索引中。这可以稍后在我们的脚本中重用。 (我是 PHP 新手,所以如果有人遇到这个知道更好方法的人,请在评论中注明我的名字,以便我学习新知识。)

    【讨论】:

      【解决方案3】:

      这是另一种简单的方法

      $sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
      if ($result = $con->query($sql_shakil)) {
      
      while ($row = $result->fetch_assoc()) {
          printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
      }
      

      Demo Link

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 2014-06-17
        • 2022-01-18
        • 2011-05-18
        • 2020-01-07
        • 2011-08-21
        • 2018-03-04
        • 2012-07-13
        • 1970-01-01
        相关资源
        最近更新 更多