Skip to content
Advertisement

convert some value from mysql query using php

using php I make a query to mysql. Inside my query, some values are in seconds (just some of them), I’d like to convert them into mm:ss. So I need to move into my “array” query and I do not understand how to move inside my query result, attribute after attribute.

Here is my db :

enter image description here

In my php code, I make the query and then for each row I put it inside an array.

$data=array(); 
$q=mysqli_query($mysqli, "SELECT * FROM TEST3612 WHERE user_id=$queryid"); 

while ($row=mysqli_fetch_object($q)) {
    //$data[]=gmdate("H:i:s", $row%86400); 
    $data[]=$row;
}

I’d like then to move into my array, and when I have the attribute CS for example, convert the value.

Here is what I tried :

foreach($data as $value) {
    if ($value['CS']) {
        $value['CS'] = gmdate("H:i:s", $value%86400); 
    }
}

I got an error. I don’t know how to move into my array, a select a element of a object. I thought I did it good but apparently no.

Thank you for you help.

Advertisement

Answer

mysqli_fetch_object returns objects, not arrays. Also you used $value instead of $value->CS inside of gmdate. So you should iterate like this:

foreach($data as $value) {
    if ($value->CS) {
        $value->CS = gmdate("H:i:s", $value->CS % 86400); 
    }
}

Alternativly you can write this directly in your while loop, so you don’t need the foreach loop. I would say this is the better solutions because you don’t write unnecessary code and performance gets improved a little bit:

while ($row = mysqli_fetch_object($q)) {
    if ($row->CS) {
        $row->CS = gmdate("H:i:s", $row->CS % 86400); 
    }

    $data[] = $row;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement