In php you can use mysql_field_name to get the field name of the specified field in a result. Someone asked me the following question.
If Employee table has three rows id,name and address. How do we fetch those names (id,name,address) using sql query in cakephp?
First of all, you can’t actually use mysql_field_name() in cakephp. But there are workarounds. Say you want to find the field names of the the table ‘Post’. Here is what you can do.
$array = $this->Post->find('all'); $array = Set::extract('/0/Post', $array); pr($array); $field_names = array_keys($array[0]['Post']); pr($field_names);
The result of the print statements will display the following
Array ( [0] => Array ( [Post] => Array ( [id] => 2 [title] => A title once again [body] => And the post body follows. [created] => 2010-02-08 07:48:03 [modified] => ) ) ) Array ( [0] => id [1] => title [2] => body [3] => created [4] => modified )
I hope this helps. Feel free to comment on this page. I’ll get notified immediately.
I presume this would require entries in the database to work? What about if the table was empty?
Comment by Nathan — May 19, 2010 @ 5:29 am
@Nathan:
something like this would work even on an empty table:
function index(){
$this->set(‘fields’,Set::extract(‘/COLUMNS/Field’,$this->Unit->query(“DESCRIBE {$this->Unit->useTable}”)));
}
Comment by Brendan Sullivan — July 30, 2010 @ 10:12 am