Gumma Mocciaro
Gumma Mocciaro

Reputation: 1215

get value from a number named column

I'm trying to retrieve the value from a number-named column in php, no success so far.

Assuming I have these columns in a msql table

id name someotherfield 200 404 500

In php (laravel actually) I execute the query

SELECT * FROM table

I'm able to print the results, and everything is fine.

Log::debug($row)

Now, if I try to take a single value from the number named field, php fails and is always returned empty

This is what I tried (using object or array is the same for me):

$row->{200} // empty
$row[200]  // empty, of course

$field = 200;
$row[$field]; // empty
$row["$field"]; // empty
$row->$field // empty

Is there a way to do so? Thanks.

Edit (my code): don't worry about object or array, any solution is valid (as you can see the 100 field has 2 as value

PHP:

$row = \App\APIList::first();

Log::debug($row);
Log::debug("My value is: " . $row['100']);
Log::debug("My value is: " . $row->{'100'});
Log::debug("My value is: " . $row[100]);

echo "My value is: " . $row['100'] . "<br />";
echo "My value is: " . $row->{'100'} . "<br />";
echo "My value is: " . $row[100] . "<br />";

LOGS:

[2016-10-12 09:51:43] local.DEBUG:     {"id":1,"function_name":"xxx","verb":"POST","usage":"xxx","call_body":"xxx ","headers":null,"isReady":1,"used":0,"failures":0,"reason":null,"last_error":null,"100":2,"101":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"300":0,"301":0,"302":0,"303":0,"304":0,"305":0,"306":0,"307":0,"308":0,"400":0,"401":0,"402":0,"403":0,"404":0,"405":0,"406":0,"407":0,"408":0,"409":0,"410":0,"411":0,"412":0,"413":0,"414":0,"415":0,"416":0,"417":0,"418":0,"422":0,"426":0,"449":0,"451":0,"500":0,"501":0,"502":0,"503":0,"504":0,"505":0,"509":0,"created_at":"2016-10-12 09:03:29","updated_at":null}  
[2016-10-12 09:51:43] local.DEBUG: My value is:   
[2016-10-12 09:51:43] local.DEBUG: My value is:   
[2016-10-12 09:51:43] local.DEBUG: My value is: 

ECHO:

My value is: 
My value is: 
My value is: 

edit 2:

php:

if ($row->{'100'} > 0) {
    Log::debug("Ok, got it");
} else {
    Log::debug("No way");
}

logs:

[2016-10-12 10:01:59] local.DEBUG: No way  

Upvotes: 0

Views: 70

Answers (2)

Gumma Mocciaro
Gumma Mocciaro

Reputation: 1215

I opened a ticket to laravel on github and it seems to be a confirmed model management bug https://github.com/laravel/framework/pull/15869 https://github.com/laravel/framework/issues/15864#issuecomment-253232963

Upvotes: 0

dimlucas
dimlucas

Reputation: 5131

Just wrap the numeric value in quotes:

If $row is an array

echo $row['200'];

Treat it the same way you treat an associative array. The number 200 is no different from a string key 'foo' for example

And if it's an object:

echo $row->{'200'};

Upvotes: 2

Related Questions