0

i want to get the field names and the row values into a single string.

example:
id | fname | gender | email
1 | john | male | [email protected]
2 | mary | female | [email protected]

select * from table where id=1  
$this->db->where('id', 1);
$query = $this->db->get('table');
$row = $query->row();
$string = $row->id . $row->fname . $row->gender . $row->email;

Desire outcome:
id:1, fname:john, gender:male, email:[email protected]
or
id, fname, gender, email, 1, john, male, [email protected]

Any advise on how to construct the sql query dynamically, many thanks.

2 Answers 2

3
$query = $this->db->query("select whatever from wherever.");
$string = "";
foreach ($query->result_array() as $row)
{
    foreach($row as $key=>$val){$string.="$key:$val,";}
}
Sign up to request clarification or add additional context in comments.

Comments

0

The only problem with selected answer is that if the query returns no records then you will not get any field names either.

You may prefer to get the field names discretely with the following command

$query = $this->db->query("select * from users");
$field_array = $query->list_fields();
$data = "";
foreach($field_array as $field){
     $data .= $field . ", "
}

2 Comments

May I ask what is the purpose of $data?
The op asked how to get results into a string. $data is just a variable to hold that string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.