Find values ​in the database starting from a session id - php

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

Related

Before fetching data from DB checking row null or not

I fetching data from DB and passing to Google Map. But sometimes in address table, lat and lng rows are being empty. So if it happens and I use that half empty array Google Map is crushes. So when I fetching data in Controller is there any option like; if row empty go next row... For example:
public function index()
{
$Data = DB::table('allestates')->whereNotNull('lat')->whereNotNull('lng')->get();
return view('home', 'Data');
}
Of course this is not proper code but, I just want to show what I am trying. Is this possible?
You can use whereNotNull:
public function index()
{
$Data = DB::table('allestates')->whereNotNull('lat')->whereNotNull('lng')->get();
if (!empty($Data)){
}
}
The filter you used (where('lat','lng')) actually means "records where the field lat has the value 'lng'".
you can add check if a field is not null by using below code:
$Data = DB::table('allestates')
->whereNotNull('lat')
->whereNotNull('lng')
->get();
if (!empty($Data)){
}

can't read data field values on views from controller in codeigniter

Getting successfully the query result from db on to the view in array variable. But not able to read individual field values on views. why print_r($sales->creditofferamount) shows nothing even has data in it.
My controller:
function edit($id = NULL)
{
$id = $this->input->get('id');
$sales = $this->Pricecomparison_model->getSalesByID($id);
$this->data['sales'] = $sales;
$this->data['id'] = $id;
$this->page_construct('pricecomparison/edit', $this->data);
}
View:
<?
print_r($sales); //this shows all data values read from db
print_r($sales->creditofferamount); //although this feild contain data in it but still does not show it.
?>

Pass variable from controller to view

In my controller, I can get the organization name but when I pass it to the view
there's an error. It said invalid argument supplied for foreach( ):
.
This is my codes.
Controller
public function index()
{
$user_id = $this->session->userdata('user_id');
$data['title'] = "User";
$getID['orgID'] = $this->userModel->getOrganizationID($user_id); // used my session user_id to
foreach ($getID['orgID'] as $orgID)
{
$org_id = $orgID->org_id;
$getName['myOrganization'] = $this->userModel->myOrganization($org_id);
foreach($getName['myOrganization'] as $orgName)
{
$name = $orgName->org_name;
$data['name'] = $name;
}
}
$this->load->view('xxxx/xxxx/xxxx',$data);
Model
public function getOrganizationID($user_id)
{
$this->db->select('org_id');
$this->db->from('organization_members');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
public function myOrganization($org_id)
{
$this->db->select('org_name');
$this->db->from('tblorganization');
$this->db->where('org_id', $org_id);
$query = $this->db->get();
return $query->result();
}
My output
First array is my result of $getID['orgID'] = $this->userModel->getOrganizationID($user_id); which I used my user_id session to get all the org_id of the user then
Second array is my result of $getName['myOrganization'] = $this->userModel->myOrganization($org_id); which I used my org_id(from my previous method) to get all the org_name of the user.
Is there going to be more then one result? Because if its only one result then you can use $query->row(); and eliminate the foreach completely.
Always check to make sure your database method worked AND that you actually got a returned value whenever you are making any database call. So i'll let you add the if condition in the database method but in short it should return FALSE if nothing came back. So thats the database method heres one way of doing it in your controller. Note this: $getID['orgID'] is very awkward. You are getting results back from the members table so call it members.
// check for the negative first - if no members came back
if( ! $members = $this->userModel->getOrganizationID($user_id) )
{
// if no results back leave this method
// pass the user id so you can echo it out in the error page
$this->showNoResultsFor($user_id) ;
}
else{
foreach ($members as $member)
{
$org_id = $member->org_id;
// etc etc etc
I'm not a codeigniter expert but looking at your code, I am wondering why you are setting:
$getID['orgID'] = $this->userModel->getOrganizationID($user_id);
First, you are setting an array $getID['orgID'] rather than just using something like $memberships = ...; I'm not sure why you are casting an array.
Secondly, you seem to be referencing a model class without instantiating it:
$this->userModel->getOrganizationID($user_id);
Perhaps codeigniter does some magic? $this refers to this instance and from the code you show, your model is likely in a separate class/file so I am unclear how $this->userModel is referenced in your method, unless you are instantiating it in your Controller's constructor?
From what I see it looks like you are getting the error because you are not supplying a valid object/array to your foreach. Perhaps start by testing you are actually getting a valid return from $this->userModel->getOrganizationID($user_id).

how to echo out data using findAllBySql in active record

This should return a list of about five locations. It returns nothing with no errors. I've tested the sql using mysql workbench. It returns the data just fine. Right now I'm writing the back end so I'm not concerned with using views or the dataprovider. I'm just making sure my back end functions work. So with that in mind, how would you return the data retrieved by findAllBySql?
class CashLogic
{
public function AllLocations()
{
$model = new Locations;
$allLocations = $model->findAllBySql("SELECT name from locations");
return $allLocations;
}
}
class SiteController extends Controller
{
public function actionIndex()
{
$model = new CashLogic;
$data = $model->AllLocations();
return $data;
}
}
The findAllBySql() method returns an array of models. From your code it seems you only want the names of locations. An alternative method is
$AllLocations=CHtml::listData(Locations::model()->findAll(),'name','name');
This will return an array of the form array('name'=>'name','name'=>'name'). A better solution would be to replace the first name with the primary key of your locations table.

CodeIgniter get_where

I’m attempting to use get_where to grab a list of all database records where the owner is equal to the logged in user.
This is my function in my controller;
function files()
{
$owner = $this->auth->get_user();
$this->db->get_where('files', array('owner =' => '$owner'))->result();
}
And in my view I have the following;
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
When I try accessing the view, I get the error :
Fatal error: Call to a member function result() on a non-object in /views/account/files.php on line 1.
Wondered if anyone had any ideas of what might be up with this?
Thanks
CodeIgniter is a framework based on MVC principles. As a result, you would usually separate application logic, data abstraction and "output" into their respective areas for CodeIgniter use. In this case: controllers, models and views.
Just for reference, you should usually have you "data" code as a model function, in this case the get_where functionality. I highly suggest you read through the provided User Guide to get to grips with CodeIgniter, it should hold your hand through most steps. See: Table of Contents (top right).
TL;DR
To solve your problem you need to make sure that you pass controller variables through to your view:
function files()
{
$owner = $this->auth->get_user();
$data['files'] = $this->db->get_where('files', array('owner =' => '$owner'))->result();
$this->load->view('name_of_my_view', $data);
}
And then make sure to use the correct variable in your view:
<?php foreach($files as $row): ?>
<span><?=$row['name']; ?></span>
<?php endforeach; ?>
<?php foreach($query->result() as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Remove the result function like so.
<?php foreach($query as $row): ?>
<span><?=$row->name?></span>
<?php endforeach; ?>
Btw. It's a much better idea to test the query for a result before you return it.
function files()
{
$owner = $this->auth->get_user();
$query = $this->db->get_where('files', array('owner =' => $owner))->result();
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;
}
public function get_records(){
return $this->db->get_where('table_name', array('column_name' => value))->result();
}
This is how you can return data from database using get_where() method.
All querying should be performed in the Model.
Processing logic in the View should be kept to an absolute minimum. If you need to use some basic looping or conditionals, okay, but nearly all data preparation should be done before the View.
By single quoting your $owner variable, you convert it to a literal string -- in other words, it is rendered as a dollar sign followed by five letters which is certainly not what you want.
The default comparison of codeigniter's where methods is =, so you don't need to declare the equals sign.
I don't know which Auth library you are using, so I'll go out on a limb and assume that get_user() returns an object -- of which you wish to access the id of the current user. This will require ->id chained to the end of the method call to access the id property.
Now, let's re-script your MVC architecture.
The story starts in the controller. You aren't passing any data in, so its duties are:
Load the model (if it isn't already loaded)
Call the model method and pass the owner id as a parameter.
Load the view and pass the model's returned result set as a parameter.
*Notice that there is no querying and no displaying of content.
Controller: (no single-use variables)
public function files() {
$this->load->model('Files_model');
$this->load->view(
'user_files',
['files' => $this->Files_model->Files($this->auth->get_user()->id)]
);
}
Alternatively, you can write your controller with single-use variables if you prefer the declarative benefits / readability.
public function files() {
$this->load->model('Files_model');
$userId = $this->auth->get_user()->id;
$data['files'] = $this->Files_model->Files($userId);
$this->load->view('user_files', $data);
}
Model: (parameters are passed-in, result sets are returned)
public function Files($userId) {
return $this->db->get_where('files', ['owner' => $userId])->result();
}
In the above snippet, the generated query will be:
SELECT * FROM files WHERE owner = $userId
The result set (assuming the query suits the db table schema) will be an empty array if no qualifying results or an indexed array of objects. Either way, the return value will be an array.
In the final step, the view will receive the populated result set as $files (the variable is named by the associative first-level key that was declared in the view loading method).
View:
<?php
foreach ($files as $file) {
echo "<span>{$file->name}</span>";
}
The { and } are not essential, I just prefer it for readability in my IDE.
To sum it all up, the data flows like this:
Controller -> Model -> Controller -> View
Only the model does database interactions.
Only the view prints to screen.

Categories