how to instantiate a class with result object in Codeigniter? - codeigniter

The documentation for result() says that we can pass the name of a class to instantiate for each result object: http://codeigniter.com/user_guide/database/results.html
I'm can't figure out correct way to do so.I need to pass few fields from the result object to the constructor.
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
please let me know if there are better ways!

You can create a static Class method in your User class that creates a user or users instances. You will need to add the appropriate instance vars to the User class.
var $username = FALSE;
var $password = FALSE;
public static function get_user_by_id($id)
{
$CI =& get_instance();
$query = $CI->db->get_where('users', array('id' => $id));
$user = $query->row(0, 'User');
return $user;
}
In the example I'm getting a reference to the CodeIgniter instance to access the database. Since you can't access the database from a Class method since it is not an object instance.

You can't.
The object instantiated can't be passed any arguments, which means you need to create a method you can use to pass these fields to the object which is instantiated:
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user)
{
$row->init_my_fields('field1', 'field2'); //instead of passing the fields through the __construct()
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}

from codeigniter documentation
$query = $db->query("SELECT * FROM users LIMIT 1;");
$row = $query->getRow(0, 'User'); // or ->row(0, 'User') in CI 3
from codeigniter /system/database/DB_result.php
public function custom_result_object($class_name)
{
...
if ($_data !== NULL)
{
for ($i = 0; $i < $c; $i++)
{
$this->custom_result_object[$class_name][$i] = new $class_name();
foreach ($this->{$_data}[$i] as $key => $value)
{
$this->custom_result_object[$class_name][$i]->$key = $value;
}
}
return $this->custom_result_object[$class_name];
}
...
}
I believe this means that CI define new class with empty constructor from the wanted class "should be available to instantiate in the scope" , and tries to set its properties with the values from the row result and then returns it

Related

Running same query in 2 different views: What's the proper way?

Just getting started into laravel and need to run the same db query for 2 different views, I know I could just create 2 controllers and perform the same query in both passing it to each view.
But, is that the proper way? Or is there a way without repeating my code?
Thanks!
Edit:
I have the following function inside a controller:
protected function getLocation($url)
{
$match = ['url' => $url];
$location = DB::table('location')->where($match)->first();
if (!$location) {
abort(404);
}
return $location;
}
the controller is returning that data to a view:
public function showsubcatandlocation($service)
{
$category = $this->getCat($service);
$location = $this->getLocation($category);
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);
}
What's the proper way to reuse the getLocation function? Or should I just copy it in the new controller? I just need to use it in those 2 views.
maybe scope Query helps?
class Location extends Model
{
public function scopeMatch($query, $url)
{
return $query->where('url', $url);
}
}
And then your two controllel methods will be
$location = Task::match($url)->first();
if (!$location) {
abort(404);
}
return $location;
$category = $this->getCat($service);
$location = Task::match($category['url'])->first();
$id = $category->id;
$locID = $location->id;
$profiles = $this->getProfileswLoc($id, $locID);
return view('category', ['profile' => $profiles]);

Can't filter data from database using getSelect()->where() Magento 2

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!
I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

How do i fetch session id from database to controller and compare codeigniter

It Return undefined index uname also try $row->name not working return false
public function profile() {
$this->load->view('header');
$uname = $this->session->userdata('uname');
$row = $this->brid_groom_fetch->get_program_specific_gender();
if ($row['uname']->uname == $uname) {
$session_id = $this->session->userdata('session_id');
var_dump($session_id);
} else {
echo 'fail';
}
}
First you need to assign session variables to an array.
Then your code
$id = $this->session->userdata('uname')
will be relevent.
To assign you can use
$this->session->set_userdata(
array(
'uname' => $row->name
)
);
Where $row->name is the value fetched from your model query.
The above sets the value in session variable 'uname'
Now you can use $id wherever you want
Also Check your autoload.php file under config dir
$autoload['libraries'] = array('session');
should be present there.
If not, then you can do the above or call
$this->load->library('session')
in your controller function.
See if that helps

Getting data from model to controller

I do have a question : I cannot pass the data from model to controller
You can see some of my codes, please help me.
It does not work!
this is my model "mymodel.php"
....
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
if($query){
foreach ($query->result() as $row);
}
$t = "EXAMPLE/{$row->code}";
function wandad() {
return $t;
}
.....
and this is my controller mycont.php
...
$this->load->model('mymodel');
$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
...
and this is my view myview.php
....
echo $new;
.....
Clearly you The model is not written properly and to corrent this simple do this
1.) I put a default value on $t
2.) I put the query >> loop on the inside function
wandad
so it can be executed once called from controller
function wandad() {
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
$t = "";
if($query){
foreach ($query->result() as $row){
$t = "EXAMPLE/{$row->code}".'<br>';
}
}
return $t;
}
Here are several issues into your model
Your Foreach function doesn't do anything
$t is not in the same namespace than wandad()
Function wandad is not defined into your model class
I'm not sure of what you wanna get with wandad() function but here's a pattern.
function yourFunction()
{
/* This will return the full query as an array */
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
/* Store variable in the same class */
$this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
return $this->t;
}
Then into your controller, do that instead :
$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);
#Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.
There is a small mistake in your code #Ernesto.that is
foreach ($query->result() as $row){
$t. = "EXAMPLE/{$row->code}".'<br>';
}
but your code was simply nice

Simplifying CodeIgniter controllers

I have a block of code I'd like to put in my CI 2.x core folder and reuse via a base controller that would be extended by all of my other controllers.
Here is the code that appears in every controller and I want to move to somewhere more central:
$data['navigation'] = generate_navigation(); // helper function
$data['country'] = code2country(); // helper function
$data['langs'] = $this->select_country_model->get_langs();
// Get copy and images for page
$query = $this->common_model->get_content('markets', 'architectural');
// Load title, description and keywords tags with data
foreach ($query as $row) {
$data['title'] = $row->page_title;
$data['description'] = $row->description;
$data['keywords'] = $row->keywords;
}
How do I put this in my base controller (MY_controller.php) and then send the data to my view from the extended controller. Do I still use $data[] = and $this->load->view('whatever', $data)?
Yeah, you can still pass this along in a $data variable, but you'll need to assign it so that you can access it from the other controller like this:
class MY_Controller extends CI_Controller {
var $data = array();
function __construct()
{
$this->load->model('select_country_model');
$this->load->model('common_model');
$this->data['navigation'] = generate_navigation(); // helper function
$this->data['country'] = code2country(); // helper function
$this->data['langs'] = $this->select_country_model->get_langs();
$query = $this->common_model->get_content('markets', 'architectural');
foreach ($query as $row) {
$this->data['title'] = $row->page_title;
$this->data['description'] = $row->description;
$this->data['keywords'] = $row->keywords;
}
}
}
Then just extend you controller with MY_Controller and you will have access to the $data with $this->data.

Resources