Filling of PHP Associated with mysql data cycle



  • <?php
        $servername = "0.0.0.0";
        $username = "user";
        $password = "1235556";
        $dbName = "name";
        $conn = new mysqli($servername, $username, $password, $dbName);
        if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
        }
        $query = "SELECT * FROM monitoring";
        $result = $conn->query($query);
        $jsonArray = array();
        if ($result->num_rows > 0) {
          while($row = $result->fetch_assoc()) {
            $jsonArrayItem = array();
            $jsonArrayItem['x'] = $row['time'];
            $jsonArrayItem['y'] = $row['players_now'];
            array_push($jsonArray, $jsonArrayItem);
          }
        }
        $conn->close();
        header('Content-type: application/json');
        echo json_encode($jsonArray);
    ?>
    

    Now I get the data in this format:

    [{"x":"2021-11-05 07:53:07","y":"17"},{"x":"2021-11-05 07:53:07","y":"13"}]And all right, there's no further construction, he's just updating the data from the database. I need the data from the bd to be kept in json with a certain length.
    My expected output json is as follows:

               [    {
    "x": "2021-11-05 07:50:07",
    "y": "17"
    },
    {
    "x": "2021-11-05 07:53:07",
    "y": "21"
    }
    {
    "x": "2021-11-05 07:56:07",
    "y": "19"
    }
    ]



    1. I'll let my waves make your code a little easier. Use array_push causes large overhead costs.
    <?php
    ...
          while($row = $result->fetch_assoc()) {
            $jsonArray[] = array( 'x' => $row['time'],'y' => $row['players_now']);
          }
    ...
    ?>
    

    1. Get the collar of the OD records.
      I think there are two records.
    var_dump( $result->num_rows );


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2