代码之家  ›  专栏  ›  技术社区  ›  Subash Kumar KR

如何在从数据库中获取数据时只获取最后一次迭代的值,我尝试了以JSON格式获取值

  •  1
  • Subash Kumar KR  · 技术社区  · 8 年前

    这是我试过的。 我已尝试从DB中获取数据。它显示从迭代开始到迭代结束的数据。我只需要最后一个迭代值。我是个彻头彻尾的傻瓜。如果您能帮忙,我们将不胜感激

       <?php
            $servername = "localhost";
            $username = "root";
            $password = "";
            $dbname = "api_db";
            $conn = new mysqli($servername, $username, $password, $dbname);
            $myarray=array();
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 
            $sql = "SELECT id, name, description FROM products";
            $result = $conn->query($sql);
    
            if ($result->num_rows > 0) {
                while($row = $result->fetch_array(MYSQL_ASSOC)) {
                    $myarray[]= $row; 
    
    
                    // echo "<pre>";
                    // print_r($myarray);
    
                    echo "<pre>";echo json_encode($myarray);
                    // echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Description :" . $row["description"]. "<br>";
                }
            } else {
                echo "0 results";
            }
            $conn->close();
    
            ?>
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   Sambhaji Katrajkar    8 年前

    将SQL查询更改为

    SELECT id, name, description FROM products order by id desc limit 1
    

    这对你很有用。

        2
  •  0
  •   Death-is-the-real-truth    8 年前

    我终于明白你的意思了-

    您需要在一个变量中获取所有记录。你终于可以编码了

    为此,请执行以下操作:-

    1、在循环外初始化数组

    2、将每条记录分配给循环内的数组

    3、对循环外的数组进行编码

    请执行以下操作:-

    <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "api_db";
        $conn = new mysqli($servername, $username, $password, $dbname);
        $myarray=array();
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        $sql = "SELECT id, name, description FROM products";
        $result = $conn->query($sql);
        $myarray = []; //Initialize array outside of the loop
        if ($result->num_rows > 0) {
            while($row = $result->fetch_array(MYSQL_ASSOC)) {
                $myarray[] = $row; //Assign each record to the array inside the loop
            }
        } else {
            echo "0 results";
        }
        $conn->close();
        echo json_encode($myarray);//Encode array outside the loop
    ?>
    
        3
  •  0
  •   Romeo Sierra    8 年前

    虽然在我看来这是重复的,但我建议如下:, 假设您不打算对DBMS中的数据集进行排序。

    使用 mysqli_data_seek ( mysqli_result $result , int $offset ) 移动遍历数据集的光标。所以对你来说

    $nor = mysqli_num_rows($result); //Number of rows
    mysqli_data_seek($resutl, ($nor - 1)); //Indices are based on 0
    

    大体上 $nor 包含记录总数。所以最后一条记录的索引是 $nor-1 。

    当然 如果要使用对查询中的数据集进行排序 ORDER BY ,那么最好的方法是附加 ORDER BY id DESC LIMIT 1 。