Can't retrieve values from foreach loop under CodeIgniter - php

I can't retrieve values from $info (as stated below) in CodeIgniter View.
Here is the scenario:
I explained everything the code.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value.
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results = $this->my_model->show_info($info);
return $results; //This is my final result which can't be achieved without using $row->address. so first I have to call this in my controller.
}
// Now I want to pass it to a view
$data['info'] = $results;
$this->load->view('my_view', $data);
//In my_view, $info contains many values inherited from $results which I need to call one by one by using foreach. But I can't use $info with foreach because it is an Invalid Parameter as it says in an error.

using $result inside foreach is not reasonable. Because in each loop $result will take a new value. So, preferably use it as an array and then pass it to your view. Besides, you should not use return inside foreach.
function info() {
{...} //I retrieve results from database after sending $uid to model.
$dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value
$result = array();
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$result[] = $this->my_model->show_info($info);
}
// Now I want to pass it to a view
$data['info'] = $result;
$this->load->view('my_view', $data);
}
to check what $result array has do var_export($result); or var_dump($result); after the end of foreach. and make sure that this is what you want to send to your view.
Now, in your view you can do:
<?php foreach ($info as $something):?>
//process
<?php endforeach;?>

Please remove return statement from
foreach($dbresults as $row) {
$info = $row->address; //This is what I need to produce the results
$results[] = $this->my_model->show_info($info);
// return $results; remove this line from here;
}
$data['info'] = $results; // now in view access by $info in foreach
$this->load->view('my_view', $data);
now $info can be access in view.
hope this will help you!

Related

Want to display data in view through controller

This is my controller
public function get_masteradmin_data()
{
$this->load->model('AppconfigModel');
$result= $this->AppconfigModel->get_masteradmin_data();
echo $result;
}
This is my Model : I am getting data from database. but , my issue is , when i use echo statement in my model , it display all documents in json format without any error. but , when i want to display all documents by storing data in a variable and pass that variable in my controller function , it does not work. What should i do to store all data in a variable and return that variable in the controller, so that i can use that data (through variable)further . What code should i need to add in my controller and model.
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
foreach($result as $r)
{
$res = json_encode($r);
}
return $res;
I also tried by returning $res and storing data in controller in a $result variable and echo that variable. but , by doing this , it only print 1 document out of 7
Try below code
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res);

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

CodeIgniter - return paramater as row

This is my code as of now which returns Hassum Harrod profile as JSON which is perfect. What I need to happen is for my parameter to be passed into the query string instead of having a name so that when the url is passed a name the query returns that person's profile from the DB. When I change the name Hassum Harrod to the variable $name I get the following error:
Unknown column 'Hassum' in 'where clause'
SELECT name, short_name, reknown, bio FROM profile WHERE name = Hassum%20Harrod
This is my code as now:
Controller
public function getPerson($name) {
// loads the DBModel.php
$this->load->model('DBModel');
$query = $this->db->query("SELECT name, short_name, reknown, bio FROM profile WHERE name = 'Hassum Harrod'");
$data['profile'] = $query->row();
$this->load->view('profileView', $data);
}
View
echo json_encode($profile);
Please Read : http://www.codeigniter.com/user_guide/general/models.html
http://www.codeigniter.com/user_guide/database/query_builder.html
Try this way
Add this method to your model it should be like this
// in your model
public function getNames($name) {
$data = array();
$this->db->select(*);
$this->db->like('name', $name);
$query = $this->get('profile');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
}
return $data;
}
Your Controller should be like this
public function getPerson($name) {
$this->load->model('DBModel');
$data = $this->DBModel->getNames($name);
// you can encode in json here
$data['profile'] = json_encode($data);
$this->load->view('profileView', $data);
}
http://www.codeigniter.com/user_guide/general/controllers.html
In view :
echo $profile;
You are using LIKE keyword in your query so we could assume there would be more than one result in return from DB. In that case you would need $query->result() instead. Secondly, even if there is just one returned row, this code:
$data['profile'] = $query->row() > 0;// assigning variable to condition (TRUE|FALSE)
will return boolean value, but not result itself.
This is simplified code for that and you can check:
<?php
$a = ['a', 'b', 'c'];
var_dump($b = $a > 0);// TRUE
Feel free to start using basic examples from docs. It will help you maintaning code:
$query = $this->db->query("YOUR QUERY");
$row = $query->row();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Again, if you expect only one possible row from DB, you can try with this code. But if you are not certain if there would be several possible rows, you have to use code for retreiving that:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
When you set this all working than you can work on converting object or array to JSON string.
It would follow syntax:
$json = json_encode($row);
If multiple rows is returned, it would be most easier to return result_array() or row_array() from DB since arrays are easily converted ti JSON, although there are suitable solutions.
After all, model that is loaded at the beginning of method is not used at all.
Docs.

How can I convert db query result to array

original I thought the $query is array object, since I can print these data to a list table like this.
my controller code
$data['dates'] = $this->calendar_model->get_cal_eventDate();
$this->load->library('table');
$this->load->view('my_test', $data);
my view code
echo $this->table->generate($dates);
but when I changed my code to try to print $tbDataArr via foreach. It didn't work. How can I convert the $query result (eventDate field values) to array object.
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
return $query;
}
$tbDataArr = $this->calendar_model->get_cal_eventDate();
foreach ($tbDataArr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
Are you using CodeIgniter? If you are you can do this
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
$result = $query->result_array();
return $result;
}
If not need more info about what your doing with your PHP.
Codeigniter, right?
Use the $query->result_array() method.
see more here:
http://codeigniter.com/user_guide/database/results.html
//Convert $query->result_array() to $query->result() after add new field in array
$result = $query->result_array();
for($i=0;$i<$query->num_rows();$i++){
//insert new field in array (test_field with value 1)
$result[$i]+=array('test_field'=>1);
$result[$i] = (object)$result[$i];
}
return $result; //equivalent to return $query->result() without new field;

turn array into object active record can use

I'm running a query and then decrypting it in the controller. After it is decrypted I was putting the results into an array and sending that to the view. The problem is with this solution I need to rewrite all of my views to parse the arrays sent instead of the active record objects sent before.
Is there a way to turn the decrypted array back into an object that will work with existing active record code in the view?
Before
Controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$data['name'] = $name;
$this->load->view('names/name_view',$data);
View:
if($name->num_rows()) > 0){
foreach($name->result() as $row){
echo $row->data;
[...]
Now
Controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$nameArray= array();
foreach ($name->result() as $row){
$x = $row;
$keys = array('id','client_id');
$unenc = array();
foreach ($x as $key=>$value){
if(! in_array($key, $keys)){
$unenc[$key]=$this->encrypt->decode($value,$this->e_key);
}else{
$unenc[$key]=$value;
}
}
array_push($nameArray,$unenc);
}
//Creates an object with the data, but doesn't work with CI active record
//foreach ($nameArray as $akey => $aval) {
// $namea -> {$akey} = $aval;
//}
//return $data;
$data['name'] = $nameArray;
$this->load->view('names/name_view',$data);
View:
if(count($name) > 0){
foreach($name as $key=>$row){
echo $row['data'];
[...]
In the second (now) controller there is some commented out code that will make an object, but it doesn't behave as expected with active record. Is there a way to take the $nameArray() array and change it into an object that will work with existing view code (such as the code in the 'before:view' above)?
Thanks!
I asked this question over on the CI forums and got some brilliant help from user mddd: http://codeigniter.com/forums/viewthread/157516/#760320
The solution ended up being to work on the mysql result object within the controller:
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$dummy = $name->result();
$ignore_keys = array('id', 'client_id');
// watch! we're getting the row as a reference so we're really changing it; not working on a copy
foreach ($name->result_object as &$row) {
foreach (get_object_vars($row) as $key=>$value){
if(!in_array($key, $ignore_keys)){
$row->$key = $this->encrypt->decode($value,$this->e_key);
}
}
}
$data['name']=$name;
$this->load->view('names/name_view',$data);
this allows me to only modify the queries in the controllers instead of the queries and all the views.

Categories