0

I was able to take the field name from the table using array_keys() but if the query results are empty, array_keys() can not be used.

query results

is there any other way that I can take the name of the field even if the result is empty?

query result empty

Query i used:

SELECT m.nama_user, m.nama_login, m.email, m.tgl_expired, m.password_web, gu.ucode_grp, gu.nama_grp_user
FROM tb_m_user m
LEFT OUTER JOIN tb_m_grp_user gu
ON m.ucode_grp=gu.ucode_grp
WHERE id_user=10

3 Answers3

1

In Codeigniter you can use...

$field_names = $this->db->list_fields('name_of_your_table');

name_of_your_table is the name of the Database Table you want the field list from.

$field_names will be an array with the field names

For more Details, Refer to https://www.codeigniter.com/userguide3/database/db_driver_reference.html?highlight=field%20names#CI_DB_driver::list_fields

TimBrownlaw
  • 5,457
  • 3
  • 24
  • 28
  • but not all fields in the table I want to take. query that I use like this SELECT m.nama_user, m.nama_login, m.email, m.tgl_expired, m.password_web, gu.ucode_grp, gu.nama_grp_user FROM tb_m_user m LEFT OUTER JOIN tb_m_grp_user gu ON m.ucode_grp=gu.ucode_grp WHERE id_user=10 – Taufiqur Rohman Nov 26 '16 at 04:24
  • 1
    if you already know what field names you wanna get, why bother selecting it from the db? that sounds illogical and a waste of a resource. just hard code it into an array or something. – RisingSun Nov 26 '16 at 04:49
  • @RisingSun when columns are aliased like in CONCAT('name', ' ', 'surname') as personal_data it doesn't sound like a waste to me at all – Bart Az. Mar 20 '19 at 23:29
0

Try this, For eg. $query_string = 'select name, role from sampledata';

$this->db->query($query_string)->list_fields();

o/p is, Array ( [0] => name [1] => role)

Jan Sršeň
  • 1,045
  • 3
  • 23
  • 46
nysha
  • 1
0

Get the query result object

$result = $this->db->get(); // OR $this->db->query()

and simply use it's methods to get all the data you need:

$return = array();
$return['list_fields'] = $result->list_fields();
$return['data'] = $result->result_array();
$return['num_rows'] = $result->num_rows();
Bart Az.
  • 1,644
  • 1
  • 22
  • 32