CodeIgniter - return paramater as row - php

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.

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;
}

echo result from function from table in database

so i am learning to write functions. Now i know how to echo stuff into a foreach but i do not know how to print a single row outside a foreach (like i only have 1 row in my table and want to print the id and username out of it) how do i do this?
my function :
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
when i call that function on my other page i call it with :
require_once 'class/class.overig.php';
$overig = new OVERIG();
i have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?
Because you are using ->fetchAll() you will always get an array of rows even if there is only one row returned. You also need to use the correct method name on your call.
So all you need to do is
$arr = $overig->gegevens();
if ( count($arr) == 1 ) {
echo $arr[0]['id'];
echo $arr[0]['username'];
}
if ( count($arr) > 1 ) {
foreach ( $arr as $row) {
echo $row['id'];
echo $row['username'];
}
}
"I have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?"
The Name of the Method you called does NOT match the Name of the Method in your Class. In your Class, You have: gegevens() but in your Call: you specified: gevens(). Unless this is just a normal Typo; you should start your Debugging from there.
In other words; your Call should have been: print_r($overig->gegevens()).
THE CLASS:
<?php
class OVERIG{
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
}
USING THE CLASS:
<?php
require_once 'class/class.overig.php';
$overig = new OVERIG();
$result = $overig->gegevens();
// TRY DUMPING THE VARIABLE: $result:
var_dump($result);
// TO ECHO OUT SOME VALUES:
if($result){
foreach($result as $key=>$item){
if(is_string($item)){
echo $item;
}
}
}

Can't retrieve values from foreach loop under CodeIgniter

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!

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;

Categories