0

I am trying to get multidimensional array out of query and for some reasons it does not work.

I use query to retrieve data from mysql.

$sql = "SELECT Id, UserID, TimeAction, Command FROM users_checked WHERE UserId = 4 AND date(TimeAction) = '2016-12-05 '";

$q=$conn->query($sql);

$data = array(); 

    while($r=$q->fetchAll((PDO::FETCH_ASSOC))){
        $data[]=$r;
    }

Array output array output

I should get array like printed below

$data = array(
        array(
            "Id" => "1",
            "UserID" => "1",
            "TimeAction" => "2016-11-29 08:00:00",
            "Command" => "Prijava"
        ),
        array(
            "ID" => "1",
            "USERID" => "1",
            "TimeAction" => "2016-11-29 10:05:14",
            "Command" => "Odjava"
        ),
        array(
            "Id" => "1",
            "UserID" => "1",
            "TimeAction" => "2016-11-29 12:22:14",
            "Command" => "PoslovniIzlazak"
        ),
        array(
            "ID" => "1",
            "USERID" => "1",
            "TimeAction" => "2016-11-29 13:32:14",
            "Command" => "Prijava"
        ),
        array(
            "ID" => "1",
            "USERID" => "1",
            "TimeAction" => "2016-11-29 16:00:00",
            "Command" => "Odjava"
        ),
    );
1
  • You have an array like you want but the representation of browser is like you show us by images. You can var_dump() to see array like you want now. Commented Dec 7, 2016 at 8:43

2 Answers 2

1

fetchAll - Returns an array containing all of the result set rows where as fetch - Fetches the next row from a result set.

So you have to use fetch instead of fetchAll if you want the data row wise.
Try this code.

while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
    $data[] = $r;
}


Reference:

Sign up to request clarification or add additional context in comments.

Comments

1

You should probably use fetch_assoc() instead of fetch_all in your for loop, this way you can push the data you want into your array for each row of your mysql query result.
It would look like this :

$data = array();
while ($row = $r->fetch_assoc()) {
    $row_array = array(
        "Id" => row['Id'],
        "UsedID" => row['UserID'],
        "TimeAction" => row['TimeAction'],
        "Command" => row['Command']
    );
    array_push($data, $row_array);
}

Please note I didn't test the code, I'm doing this by head. Also, I'm guessing you didn't mean to write all Ids to "1" in your example.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.