skip to Main Content

I’m trying to store the date from DateTime from PhpMyAdmin into an array in my code. For some reason, It only applies the last date to the position [0] from my array. Please help.

This is what I tried:

$id = $_SESSION['userId']; 
      $dBname = "infosensor";
      $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);

      $sql = "SELECT dias FROM `$id`;";
      $result = mysqli_query($conn, $sql);
      $resultCheck = mysqli_num_rows($result);

      if ($resultCheck > 0)
      {
        while ($row = mysqli_fetch_assoc($result))
        {

          $horario = $horario .'"'.(date('H:i:s', strtotime(str_replace('.', '-', $row['dias'])))). '",';    

          $arr = array($horario);
        }
      }


      echo $arr[0];

The result that I get from the code I tried is:

"16:29:47","16:30:07","16:33:55","16:34:25",... 

All of the at position [0]

I would need to when going into the array -> arr[0] = “16:29:47” when I want the position 1 I just use arr[1] = “16:30:07″…

3

Answers


  1. Try changing this line like this:

    $horario = (date('H:i:s', strtotime(str_replace('.', '-', $row['dias']))));    
    
    $arr[] = explode(',', $horario);
    
    Login or Signup to reply.
  2. First you need to initialise $arr = []
    Then you can achieve this by explode.

    $id = $_SESSION['userId']; 
    $dBname = "infosensor";
    $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
    
    $sql = "SELECT dias FROM `$id`;";
    $result = mysqli_query($conn, $sql);
    $resultCheck = mysqli_num_rows($result);
    
    $arr = [];
    if ($resultCheck > 0)
    {
        while ($row = mysqli_fetch_assoc($result))
        {
    
            $horario = $horario .'"'.(date('H:i:s', strtotime(str_replace('.', '-', $row['dias'])))). '",';
        }
    
        if(!empty($horario)){
            $arr = explode(',', $horario);
        }
    }
    print_r($arr);
    
    Login or Signup to reply.
  3. $arr = []; // define array here
    while ($row = mysqli_fetch_assoc($result))
    {
    
          $horario = $horario .'"'.(date('H:i:s', strtotime(str_replace('.', '-', $row['dias'])))). '",';    
    
          $arr[] = $horario; // add [] here and remove array()
    }
    //    print_r($arr);
    echo $arr[0];
    

    Output

    Like this

    arr[0] = “16:29:47” , arr[1] = “16:30:07”

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search