18

I have mysql table with collumns like 'operation.date', 'operation.name' and etc. After fetching that table data as object with $mysqli->fetch_object() i get this (print_r of row):

stdClass Object
(
[id] => 2
[operation.date] => 2010-12-15
[operation.name] => some_name
)

how do I acces operation.date and operation.name and all other weirdly named object properties?

hakre
  • 193,403
  • 52
  • 435
  • 836
egis
  • 1,404
  • 2
  • 11
  • 24
  • 4
    This is a duplicate. The answer is, it's not a valid property. You should change it. But you can use `$obj->{'operation.date'}` to access it. – Gordon Mar 18 '11 at 11:07
  • possible duplicate of [Hyphens in Keys of Object](http://stackoverflow.com/questions/2925044/hyphens-in-keys-of-object) and also [How do I access this object property](http://stackoverflow.com/questions/758449/php-how-do-i-access-this-object-property) – Gordon Mar 18 '11 at 11:14
  • Sorry for that. Was searching but not for hyphens. – egis Mar 18 '11 at 11:25
  • No problem. Wasnt that easy to find anyway. – Gordon Mar 18 '11 at 11:26

5 Answers5

45

Specify aliases in your SQL query like SELECT column AS nameWithoutDots ...
or access these properties with $object->{'operation.name'}
or cast the object to array like this: $obj = (array)$obj; echo $obj['operation.name'].

rik
  • 8,592
  • 1
  • 26
  • 21
  • 1
    +1 for telling the OP how to cure the cause and not the symptoms – Gordon Mar 18 '11 at 11:15
  • 1
    I know about aliases, but too much effort to write miles long query with all the columns as aliases :) Since your answer was most informative I will accept it ;) Thanks for all the answers. – egis Mar 18 '11 at 11:24
15

The correct way of accessing properties with a dot should be :

echo $object->{"operation.date"}
peipei
  • 1,407
  • 3
  • 14
  • 22
6

To access these attributes you need to wrap them with curly brackets:

echo $object->{"operation.date"} //2010-12-15

If you set an attribute this way the offending symbol gets removed, allowing you to access the attribute as echo $object->operationdate //2010-12-15

Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
2

Change the sql to return valid property names using the 'as' feature

eg. select operation.date as date

Shaun Hare
  • 3,771
  • 2
  • 24
  • 36
0

You can get assoc array instead object by using $mysqli->fetch_assoc()

Dmitry
  • 2,057
  • 1
  • 18
  • 34