I have been trying to figure out how to load the data in a query to an array.
$query->row() //only brings back a single row of data when there are more entries in the database.
If I just use a foreach loop and echo in the model code below, The data is simply displayed on the screen. It's not in a variable or an array. It is just text on the screen all jammed together.
I had a really hard time trying to find a code example that would show me how to use the
$this->db->get_where('table' array('column' => $var);
I finally found it but then the example on codeigniters site only echos the query back to the screen.
http://ellislab.com/codeigniter/user-guide/database/results.html
This is not useful for production.
My controller code is:
public function record(){
/*
* Here the id is being passed to the record
* function to retieve the parent and childrens data
*
*/
$getid['id'] = $this->uri->segment(3);
$accld = $getid['id'];
$data = array();
$this->load->model('account');
$account = new Account();
$account->load($getid['id']);
$data['account'] = $account;
$this->load->model('children');
$children = new Children();
$children->accld($getid['id']);
$data['children'] = $children;
$this->load->view('childeditdisplay', $data );
}
}
My Model code is this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$c_data = array();
foreach ($query->result() as $row){
$c_data[] = $row ;
}
return $c_data;
/*
* Note:
* I need to figure out how to load to an array to pass back to the
* controller to pass to the display
* I can echo to the screen the results but that is uncontrolled.
*
*/
}
If I do this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
foreach ($query->result() as $row){
echo $row->id ;
// and all the other fields below here
}
}
My rows are echoed to the screen. But there is no control. So any help in getting control of my data would be greatly appreciated.
ANSWER
This is finally what worked to bring back all the results and not just one row.
/**
* Populate from an array or standard class.
* #param mixed $row
*/
public function populate($row) {
foreach ($row as $key => $value) {
$this->$key = $value;
}
}
public function accld($id) {
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$this->populate($query->result());
}
Just do
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$_array = $query->result_array();
Do whatever with $_array.
Related
I am developing a system that uses Maatwebsite to read and write data to the database from an excel sheet, which is working fine. Now before inserting the data, the system checks for the entries in parent table. And if there is any record that matches the record of the sheet, the system inserts foreign key to the child schema and if there's not, the system creates one first and then insert it's id as foreign key.
Here's the import class:
public function collection(Collection $rows){
$sub_chap = SubChapter::where(['chap_id' => $this->chap_id])->get();
$chapter = Chapter::where(['chap_id' => $this->chap_id])->first();
$author = Author::where(['author_status' => 1])->get();
$book = $chapter->book_id;
$author_id = 0;
$sub_chap_id = 0;
/* Working perfectly fine here...
foreach($author as $a){
echo $a->a_name."\r";
}
*/
foreach ($rows as $row){
if($row['quote_english'] != ""){
foreach($sub_chap as $sub){
if(trim($sub->sub_chap_english) == trim($row['sub_chap_english'])){
$sub_chap_id = $sub->sub_chap_id;
break;
} else{
$sub_chap_id = 0;
}
}
if($author->count() > 0){
foreach($author as $athr){
$author_id = (trim($athr->author_name) == trim($row['author_name']))? $athr->author_id : $author_id = 0;
}
}
if($author_id == 0){
$author = Author::create([
'author_name' => $row['author_name'],
...
...
'author_status' => 1,
]);
$author_id = $author->author_id;
}
$quote = Quote::create([
'quote_english' => $row['quote_english'],
'author_id' => $author_id,
'sub_chap_id' => $sub_chap_id,
'chap_id' => $this->chap_id,
'book_id' => $book
]);
}
}
}
It's saying:
Trying to get property 'author_name' of non-object
I know this error comes when you try to access an object's property from a non-object instance. get() is returning the collection object as usual and working fine outside the foreach() loop. what i can't figure out is why it's not working inside the loop. Any help would be appreciated!
I still can't figure out why it's saying that and seems like no else also. So I think it's about time I post the solution I came up with. I found a way around it, So, basically what I did was I stored the whole collection to a global variable and accessed it in the loop.
Here's the code:
/**
* Global variable for raavi's data.
*/
public $author;
/**
* Construction function.
*
* #param int $id
* #param Collection $arr
*/
function __construct($arr) {
$this->author= $arr;
}
/**
* This method is responsible for inserting the excel
* sheet's rows data to the database schema.
*
* #param Collection $rows
*/
public function collection(Collection $rows){
// other code as it is...
foreach($this->author['author'] as $athr){
$author_id = (trim($athr->a_name) == trim($row['author_name']))? $athr->a_id : 0 ;
}
}
and in my importing controller's import method:
$quotes = Excel::import(new QuotesImport(compact('author')));
Working fine till now. If there's some improving or anything that needs to be change, kindly feel free. I would appreciate it.
I am newbie in codeigniter. If I have a model like this :
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row();
}
And I try to accessed it from may controller :
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
How to Generating Query Results, thanks for the help.
EDIT
I am new in CI, my question is : let's say I want to get the 'nama_user' into an a variable like this :
foreach ($data as $d) {
$name = $d['nama_user'];
}
echo json_encode($name);
I use firebug, it gives me null. I think my foreach is in a problem
In order to return an array from your model call you can use result_array() as
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->result_array();//<---- This'll always return you set of an array
}
Controller File with your query code
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
//Generating Query Results like this because you use $query->row();
$data->nama_user;
$data->keluhan;
$data->email;
$data->addresed_to;
$info_json = array("nama_user" => $data->nama_user, "keluhan" => $data->keluhan, "email" => $data->email, "addresed_to" => $data->addresed_to);
echo json_encode($info_json);
}
MODEL.PHP
public function get_data_for_reminder($id) {
$this->db->select('nama_user, keluhan, email, addresed_to');
$query = $this->db->get_where('tbl_requestfix', array('id_request' => $id));
return $query->row_array();
}
//Generating Query Results if use $query->row_array(); in model file
Controller.php
function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
foreach($data as $row)
{
$myArray[] = $row;
}
echo json_encode($myArray);
You fetched data for selected id it means you get a single row, if you want to get "nama_user" then in your controller:
public function reminderIT() {
$id = $this->input->post('id');
$data = $this->model_request->get_data_for_reminder($id);
$name = $data->nama_user;
echo json_encode($name);
}
I've been trying to get the results from my query for the past two hours, in my model I have this
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
in the controller
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$model=new QuoteForm();
if(isset($_POST['QuoteForm']))
{
$model->attributes=$_POST['QuoteForm'];
if ($model->validate())
{
$priceTable=new CityFareFinal;
$priceTable->fromm=$model->pickupL;
$priceTable->too=$model->dropoffL;
$priceTable->type_of_car=$model->type;
this->render('result',array('model'=>$priceTable))
}
}
else
{
$this->render('index',array('model'=>$model));
}
}
and in the view
<div id="moduleResult">
<span><?php echo $model->getQuotes() ;?><------ Here</span>
</div>
but it always give me an error saying "Object of class CDbCommand could not be converted to string ", what can I do to get the results of my query made in the model???
Regards
Gabriel
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select fromm from city_fare_final');
$data->queryRow();
return $data ;
}
Your getQuotes() return Object of class CDbCommand:
+ You returned $data in the function instead of $data->queryRow().
By the way, you cannot use echo for array data.
The below example is used for fetching data from DB to view by using DAO with Yii: I suppose you have Person model and Person controller
In your Person model:
function getData() {
$sql = "SELECT * from Person";
$data = Yii::app()->db
->createCommand($sql)
->queryAll();
return $data;
}
In your controller:
function index(){
$data = Person::model()->getData();
$this->render('your_view',array(
'data'=>$data,
));
}
In your view: you can foreach your data to echo items in the array data:
<?php foreach($data as $row): ?>
//show something you want
<?php echo $row->name; ?>
<?php endforeach; ?>
$data->queryRow(); returns result in array format. Your code is returning $data which is an object not result of query. That's why you are getting this error.
If you want to fetch single value you can use $data->queryScalar();
In case of queryRow() your code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select * from city_fare_final');
$result = $data->queryRow();
return $result ; //this will return result in array format (single row)
}
for a single field value you code will be
public function getQuotes()
{
$data = Yii::app()->db->createCommand('Select xyz from city_fare_final');
$result = $data->queryScalar();
return $result; //return single value of xyz column
}
I hope this will help.
below sample code to traverse rows returned by queryAll
$connection = Yii::app()->db;
$command = $connection->createCommand("Select * from table");
$caterow = $command->queryAll(); //executes the SQL statement and returns the all rows
foreach($caterow as $retcat )
{
echo $retcat["ColumnName"] ;
}
Returns Arrary of rows with fields
Model: Notices.php:
---------------------------------
public function getNoticesBlog($offset = 0){
$dataResult = Yii::app()->db->createCommand()->select('*')->from($this->tableName())
->andWhere("delete_flg=:delete_flg",array(':delete_flg'=>0))
->andWhere("publish=:publish",array(':publish'=>1))
->limit(3)->offset($offset)->order('created_on DESC')->queryAll();
return $dataResult;
}
Controller: NoticesController.php
$firstNotices = Notices::model()->getNoticesBlog(0);
$secondNotices = Notices::model()->getNoticesBlog(3);
$thirdNotices = Notices::model()->getNoticesBlog(6);
$this->render('Notices',array(
'firstNotices'=>$firstNotices,
'secondNotices'=>$secondNotices,
'thirdNotices'=>$thirdNotices,
)
);
I'm wondering what would be best to do. Right now I have running a query to see if I have any results returned and if none are returned I return NULL.
On my controller I send that resultset whether it be an object or NULL to my table and it echos the rows on the view page.
For my tables I am using the jquery datatables plugin. I'm trying to figure out how I can have it handle the data when the sent value is NULL that way it doesn't show me an error when it hits my foreach loop.
Controller:
$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;
Model:
/**
* Get news articles
*
* #return object
*/
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return NULL;
}
View:
$tmpl = array ( 'table_open' => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');
$this->table->set_template($tmpl);
foreach ($news_articles as $row)
{
$checkbox_data = array(
'name' => 'newsarticles',
'id' => $row->id
);
$this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate();
I typically respond using JSON and then add a "success" type boolean and then check that value before trying to process any data. It also allows for an easy way to place an error message in the response if something goes wrong.
Just another idea
Model
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return FALSE;
}
Controller
$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
$this->data['news_articles'] = $news_articles;
$this->data['success'] = TRUE;
}
In the view
if($success)
{
foreach ($news_articles as $row)
{
//....
}
}
else echo "No results found !";
Just return an empty array from the model, if there are not results. That way your foreach won't break. It just won't loop over anything.
I have a simple recursive array function that looks like this:
function recursive_array($results) {
global $DBH;
if (count($results)) {
echo $res - > Fname;
foreach($results as $res) {
$STH = $DBH - > query("SELECT FID,FParentID,Fname FROM list WHERE FParentID = ".$res - > FID."");
$fquerycount = $STH - > rowCount();
$STH - > setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH);
}
}
}
$FID = isset($_GET['FID']) ? $_GET[' FID'] : 0;
$STH = $DBH - > query("SELECT FID,FParentID,Fname FROM list WHERE FParentID ='0' ");
$STH - > setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH);
I also have created a simple query class that looks like this:
class queryloop {
function __construct($args) {
global $DBH;
$table = $args['tbl'];
if (array_key_exists('orderby', $args)): $orderby = 'ORDER BY '.$args['orderby'];
else: $orderby = '';endif;
if (array_key_exists('groupby', $args)): $groupby = 'GROUP BY '.$args['groupby'];
else: $groupby = '';endif;
if (array_key_exists('start', $args)): unset($orderby);$start = $args['start'].' , ';
else: $start = '';endif;
if (array_key_exists('limit', $args)): $limit = 'LIMIT '.$start.' '.$args['limit'];
else: $limit = '';endif;
// UNSET the previously used array keys so they are not use again to create the query string
unset($args['tbl']);
unset($args['orderby']);
unset($args['groupby']);
unset($args['start']);
unset($args['limit']);
// Checks if args still an array after UNSET above. If not empty create the query string
if (!empty($args)): foreach($args as $k = > $v): $querystr. = 'AND '.$k.' = \''.$v.'\'';endforeach;
// If args array empty return empty query string
else: $querystr = '';endif;$STH = $DBH - > query("SELECT * FROM ".$table." WHERE key = '".KEY."' ".$querystr." ".$groupby." ".$orderby." ".$limit." ");
if ($STH): $STH - > setFetchMode(PDO::FETCH_OBJ);
while ($row = $STH - > fetch()): foreach($row as $key = > $val):
// check if value is numeric //
if (is_numeric($row - > $key)): $data[$row - > ID][$key] = $row - > $key;
// check if value is array //
elseif(is_array($row - > $key)): $data[$row - > ID][$key] = $row - > $key;
// check if value is not numeric or array convert to html entities //
else: $data[$row - > ID][$key] = htmlentities($row - > $key);endif;endforeach;endwhile;$this - > data = json_encode($data); // return json array if data
else: $this - > data = ''; // return 'null' if no data
endif;
}
}
$args = array('tbl' = > 'atable', 'limit' = > '5', 'start' = > '200', 'orderby' = > 'ID DESC');
$loop = new queryloop($args) // run the loop etc.
How do I turn my recursive array into something like the class queryloop so that I can "pull out" json endoded data I know that this (below) is totally wrong but what ever I do I cannot get a correctly formed json array or even anything to return form my attempted class below. Help would be much appreciate. Thanks in advance.
class recloop {
function __construct() {}
function recursive_array($results) {
global $DBH;
if (count($results)) {
foreach($results as $res) {
echo $res - > Name;
$STH = $DBH - > query("SELECT * FROM atable WHERE ParentID = ".$res - > ID."");
$fquerycount = $STH - > rowCount();
$STH - > setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH);
}
}
}
function recursive_start() {
global $DBH;
$ID = isset($_GET['ID']) ? $_GET['ID'] : 0;
$STH = $DBH - > query("SELECT * FROM atable WHERE ParentID = '".$ID."' ");
$STH - > setFetchMode(PDO::FETCH_OBJ);
recursive_array($STH);
}
}
How do I turn my recursive array into something like the class queryloop so that I can "pull out" json endoded data I know that this (below) is totally wrong but what ever I do I cannot get a correctly formed json array or even anything to return form my attempted class below. Help would be much appreciate. Thanks in advance.
To answer your question, I would say it's not specific if you encapsulate your routines into objects or not that much, but that you take care that each object is there for a sole purpose. For example:
One object is fetching the data from the database.
One object/composite/array is the data-structure, representing the data.
One object or function is taking over the job to convert/encode the data into json.
Within your code I see that you right now are only running SQL-queries. The data fetched from the database server is not stored into a return variable at all, it get's directly consumed while being recursively processed. I assume you do this for debugging reasons.
So the actual question is, what do you want to do? You write that you want to encode an object into json output, which is perfectly possible with json_encodeDocs, however I think you refer to some specific data, like the entity (data) of the most parentId or something.
Following is some mock-up code based on your code for reading purposes (not tested, must not match your needs) that can provide all parent objects of that one specified by ID by using recursion. The recursion has been criticised because this can result in running a lot of queries - and additionally there is risk to create an endless loop which will result in a recursion stack overflow - your program crashes then.
To handle that alternatively, this is bound to the database design (which should be done before the design of the code, and I don't know your database design nor what you actually want to do, so I can't add assumptions for that). So the following code takes care of already queried objects only while still using recursion as the strategy to query your database.
For the actual data-structure I opted for an array of plain old PHP objects, keyed by the ID field from the database (which I assume that it exists per record):
/**
* HTTP Get Parameter (Input)
*/
class HTTPGetParameter {
private $name;
private $default;
public function __construct($name, $default = '') {
$this->name = (string) $name;
$this->default = (string) $default;
}
/**
* #return string
*/
public function getValue()
{
return isset($_GET[$name]) ? $_GET[$name] : $this->default;
}
/**
* #return int
*/
public function getValueInt()
{
return (int) $this->getValue();
}
/**
* #link http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
*/
public function __toString()
{
return $this->getValue();
}
}
/**
* Data Provider
*/
class PDODataProvider
{
private $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
/**
* #return array
*/
public function findAllATableParents($id)
{
return $this->findAllOn('atable', 'ParentID', $id);
}
public function findAllBTableParents($id)
{
return $this->findAllOn('btable', 'ParentID', $id);
}
private function findAllOn($table, $field, $id)
{
$id = (int) $id;
$objects = array();
$sql = sprintf("SELECT * FROM %s WHERE %s = '%d'", $table, $field, $id);
$pdoStatement = $this->pdo->query($sql);
$pdoStatement->setFetchMode(PDO::FETCH_OBJ);
foreach($pdoStatement as $parent)
{
$parentId = $parent->ID;
# parents that had been queried are skipped
if (isset($objects[$parentId]))
continue;
$objects[$parentId] = $parent;
# add parent objects by recursion
$objects += $this->findAllParents($parentId);
}
return $objects;
}
}
/**
* main
*/
$data = new PDODataProvider($DBH);
$id = new HTTPGetParameter('ID', 0);
$objects = $data->findAllParents($id->getValueInt());
echo json_encode($objects);
I hope this example is helpful for you to answer your question.