Store array of arrays in codigniter session - php

I have a query in CodeIgniter model, like:
$query = $this->db->get('subscriber');
The above query is returning 474 rows as a result.
Now I want to iterate these value in my view in table format so I am storing the value in a PHP native session, like:
$_SESSION['list'] = $query;
But when I am iterating over this loop in view, I am not getting the desired result.
The value of $_SESSION['conn_id'] is '0'
The value of $_SESSION['result_id'] is '0'
The value of $_SESSION['result_array'] is 'Array'
The value of $_SESSION['result_object'] is 'Array'
The value of $_SESSION['custom_result_object'] is 'Array'
The value of $_SESSION['current_row'] is '0'
The value of $_SESSION['num_rows'] is '474'
The value of $_SESSION['row_data'] is ''
While using
foreach($_SESSION['list'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
I know this is not the method to do this. How can I access the quesryset result in CodeIgniter view?
Can we use the queryset data directly or not?

What you would typically do is something like this
//model.php
class Subsrciber_Model extends CI_Model
{
public function get_subscribers()
{
return $this->db->get('subscriber');
}
}
//controller.php
class Subscribers extends CI_Controller
{
public function subscribers()
{
$this->model->load('Subscriber_Model');
$data = $this->Subscriber_model->get_subscribers();
$this->load->view('view', $data);
}
}
//view.php
<div>
<?php foreach ($data->result() as $row): ?>
<p><?=$row->conn_id?></p>
<? endforeach; ?>
</div>

Try this:
$query = $this->db->get('subscriber')->result_array();

Are you sure that an array is being returned from your query? From the output of your SESSION it looks like you are treating an object like an array.
Try doing this in your model
$query = $this->db->get('subscriber')->result_array();

Related

print query values from session to view error Undefined index: DCM_TITLE

I'm new to CodeIgniter.
I have two functions in my Controller. In one with post method I create data array and then put that array to session. In another function I need another values, like title or date (because in session I only have ID values), so I send ID values to Model functions and then I load view with data I need. Then in view I print out the data I need. But I get an error saying
Message: Undefined index: DCM_TITLE
Controller function code:
public function visi_registravimas(){
$this->output->enable_profiler(TRUE);
$DCM_ID = $_SESSION['DCM_ID'];
$PRD_ID = $_SESSION['PRD_ID'];
$result['documents'] = $this->Skaitikliu_registras_model->setDocument($DCM_ID);
$result['periods'] = $this->Skaitikliu_registras_model->setPeriod($PRD_ID);
$this->load->view('skaitikliu_registras/visi_registravimas_view',$result);
}
model:
public function setDocument($DCM_ID){
$query = $this->db->query("SELECT * FROM RA_DOCUMENT WHERE DCM_ID='$DCM_ID'");
return $query;
}
public function setPeriod($PRD_ID){
$query = $this->db->query("SELECT * FROM RA_PERIOD WHERE PRD_ID='$PRD_ID'");
return $query;
}
And this is how I print data in view:
<body>
<?php $this->load->view('navbar_view'); ?>
<?php foreach($documents as $document) : ?>
<?php echo $document['DCM_TITLE']; ?>
<?php endforeach ?>
</body>
Change this in Model Query:
return $query;
return $query->result_array();
result_array() returns the query result as a pure array Format.
Note:- For More Information regarding this
https://codeigniter.com/userguide3/database/results.html
To expand on the #KUMAR answer I would also advise to start using the query builder instead of writing the queries yourself.
This is a good practice so if in any case you change your database from MYSQL to postgresql or any other database engine you don't need to change anything about your models.
In this case your model functions would look like this:
public function setDocument($DCM_ID){
$q = $this->db->where('DCM_ID', $DCM_ID)->get('RA_DOCUMENT');
return $q->result_array();
}
public function setPeriod($PRD_ID){
$q = $this->db->where('PRD_ID', $PRD_ID)->get('RA_PERIOD');
return $q->result_array();
}
This way you get cleaner code and code that can be maintained for longer.

Find values ​in the database starting from a session id

I need display the value in the ga845_clients table ​​in the atacado column, that have 's' or 'n' recorded, but they return blank.
Then when I call <?php echo $this->session->userdata('usu_id');?> in view, the ID is displayed.
I have checked that usu_id is the session ID and the same value from id of table ga845_clientes.
I created the following codes:
Model (Cliente_model.php):
public function getAtacadista($id) {
$this->db->select("atacadista");
$this->db->where('id', $this->session->userdata("usu_id"));
$query = $this->db->get('ga845_clientes');
return $query->result();
}
Controller (Cliente.php):
public function getAtacadista() {
$this->load->model('cliente_model');
$this->load->view("carrinho", $data);
$data['atacadista'] = $this->cliente_model->getAtacadista($id);
}
View (carrinho.php)
echo 'test1:' .$data['atacadista'];
echo 'test2:' .$atacadista;
Remember, $data['atacadista'] dont exists on view, only $atacadista
Also move down the " load view " line, as everton suggested, they are swapped and $data need to be before.
And lastly, as a tip, session userdata can contain a bunch of info, and you should pass the name of the session, not of the value, maybe usu_id is a value inside an array, not the array itself.
You can try the following in your controller
public function getAtacadista() {
$this->load->model('cliente_model');
$data['atacadista'] = $this->cliente_model->getAtacadista($id);
$this->load->view("carrinho", array("data"=>$data));
}
You should place the $data variable assign before the load view.
Because you are not sending your data to the view. change the sequence of your statements.
public function getAtacadista() {
$this->load->model('cliente_model');
$data['atacadista'] = $this->cliente_model->getAtacadista($id);
$this->load->view("carrinho", $data);
}

Model returning null values

I'm a new bee to web development. I need to get data (some columns) from the job table and filter it according to the user name in the session and a status value (status is a TINYINT there for contains 0 and 1).
Here is my model:
public function show_work() {
$user_name = $this->session->userdata('Name');
$this->load->database();
$this->db->select('jbStageID, Description, StartDate, SpecialDetails, EstimateTime, Instrauctions');
$this->db->where('Name',$user_name);
$this->db->where('status','0');
$rset=$this->db->get('job');
$result=$rset->result_array();
}
Here is my controller:
public function employees()
{
$this->load->model('show_details');
$result= $this->show_details->show_work();
$data = array();
$data['inbox'] = $this->show_details->show_work();
var_dump($result);
echo "<pre>";
print_r($data);
echo "</pre>";
die();
}
The issue is I don't get values from the database but value null with empty array.
The result is like this:
Array(
[inbox] =>
)
You need to use the return to return the data as below in the model's last line:
$result=$rset->result_array();
return $result;
you missed $this->db->from
that means from table in sql query.

loadmodel dont work why?

in the sections_controller i use loadmodel to print username in sections/index file but i get error :
Notice (8): Undefined variable: user [APP\views\sections\index.ctp, line 3]
public function index ()
{
$this->loadModel('User');
$user = $this->User->find('all');
$this->Section->find('threaded', array('order' => array('Section.created ASC')));
$this->set('data','user');
}
in the sections/index
<div><?php echo $user['User']['username']; ?></div>
You have a typo, try :
$this->set('data',$user);
and then in your view :
<div><?php echo $data['User']['username']; ?></div>
Hope this helps !
You're not assigning the variable properly, try this instead:
$this->set('user', $user);
$user pointing to your find result and set as user, since that's what you're trying to call in your view. Or alternatively use the compact notation to achieve the same:
$this->set(compact('user'));
What you are doing now is setting a variable called data with the string value user, so when you would do this in your view:
echo $data;
It would return user as a string in your view.
EDIT
Since a find('all') will return an array, make sure you loop over the results in your view as well, like this:
foreach($user as $u) {
echo $u['User']['username'];
}
Or if you want a specific result, call it's array key, which for the first user would be:
echo $user[0]['User']['username'];

passing sql query results from controller into view with code igniter

So I'm having this problem, it should be pretty simple, but I don't know why I can't figure it out. I"m new to the whole idea of MVC, and I'm trying to pass a database query from my controller into a view and display the results in the view. The way I'm doing it now says "undefined variable, sql" when I load the view. This is what I have:
CONTROLLER
function make_login()
{
//Select list of departments for dropdown
$this->load->database();
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
$this->load->view('siteheader.php');
$this->load->view('makelogin.php', $sql->result_array());
$this->load->view('sitefooter.php');
}
VIEW
<?php
foreach($sql->result_array() as $row)
{
echo $row['departmentName'];
}
?>
(If I just echo it out in the controller, it displays the results)
Any help would be awesome...
THANKS!
few tips ~
your make_login should be in a model. your controller will look something like this:
function make_login
{
$this->load->model('login_model'); // whatever you call it
$data['departments'] = $this->login_model->get_departments();
/* note - you don't need to have the extension when it's a php file */
$this->load->view('siteheader');
$this->load->view('makelogin', $data);
$this->load->view('sitefooter');
}
now in your model, have something like:
function get_departments()
{
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
return $sql->result();
/* you simply return the results as an object
* also note you can use the ActiveRecord class for this...might make it easier
*/
}
and finally, your view:
<?php
foreach($departments as $store)
{
echo $store->name . '<br />'; // your fields/whatever you want to output.
}
?>
The SQL query should be done in the model.
Cheap mnemonic device: the D in model = database.
In the Controller, you assign part of the $data array to the results of the query:
$this->load->model('blog_model');
$data['posts'] = $this->blog_model->getPosts();
// Load the view with the data
$this->load->view('blog', $data);
In the Model, you do the actual query:
public function getPosts()
{
// Method chaining supported in PHP 5
$this->db->select('*')->from('posts');
// Assign the query object to a variable
$query = $this->db->get();
// We don't want to return an empty result, so let's handle that error somehow
if (!$query->num_rows() > 0) {
die("There are no posts in the database.");
}
// Make a new array for the posts
$posts = array();
// For the purposes of this example, we'll only return the title
foreach ($query->result() as $row) {
$posts[$row->id] = $row->title;
}
// Pass the result back to the controller
return $posts;
}
Now, in the view, each element of $data will be its own variable:
<div class="post">
<?php foreach ($posts as $id => $title) : ?>
<h1 class="post-title"><?php echo $title; ?> (ID: <?php echo $id; ?>)</h1>
<p class="post-content">
.......
</p>
<?php endforeach; ?>
</div>
That's it!
It seems that either CI is confusing you or you are also new to PHP. They are just functions so you can't pass variables like that.
When passing an associative array it will take the key and make that into a variable with the value in the array, using native PHP functions. What Ross said is exactly what you are supposed to do.
Model: all database stuff
Controller: uses models to pass variables to views
View: outputs the variables (a view should never have any sql in it)
Also note that result and result_array have the same data but result returns objects and result_array returns associative arrays.
foreach($array as $row)
{
echo $row['departmentName'];
}
?>
You need to pass the $array in.
I am not sure what ->load->view() does and how it treats the incoming parameters.

Categories