Codeingniter3 echo a single element of an associative array - php

Let's assume I have this controller function
public function index(){
$this->load->model('model_users');
$clienteemail = $this->session->userdata('email');
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
$data['title']='La Giumenta Bardata Dashboard'; //array per titolo e dati passati
$this->load->view('auth/template/auth_header', $data);
$this->load->view('auth/template/auth_nav', $cliente);
$this->load->view('auth/clienti/auth_sidebar');
$this->load->view('auth/clienti/client_dash');
$this->load->view('auth/template/auth_footer');
}
model_users is a model that query the db with this function:
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query) {
$row = $query->row();
$cliente['nome'] = $row->nome;
return $cliente;
} else {
echo "errore nella ricerca del nome";
}
What I'm trying to do is to use an user email from the session data to retrieve info from the db table.
so I start to retrieve just the name of the user.
The function works, but when in the view I use echo $nome;
I have an error about the conversion between array and string... that's normal, I know, but if I do
print_r($nome);
my output is: Array[0] => 'Pippo'
I just want to output the content of the array.
How can I achieve this?

It looks like you've made a bit of a typo..
Your model:
$row = $query->row(); // Fetch the entireuser
$cliente['nome'] = $row->nome; // Set the name to a value. $cliente isn't defined yet..
return $cliente; // Return the entire $cliente array.
Your Controller:
You are using the above model method and assuming it is returning just the name. It is actually returning the full user.
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);
Change your model code to the following and it should work as expected.
public function lettura_dati($clienteemail)
{
$this->db->where('email', $clienteemail);
$query = $this->db->get('user');
if ($query && $query->num_rows() > 0) { // Ensure we have got at least 1 row
$row = $query->row();
return $row->nome;
} else {
echo "errore nella ricerca del nome";
}
}

return $row->nome;
instead of:
$cliente['nome'] = $row->nome;
return $cliente;
OR
$cliente_data = $this->model_users->lettura_dati($clienteemail);
$cliente['nome'] = $cliente_data['nome'];
instead of:
$cliente['nome'] = $this->model_users->lettura_dati($clienteemail);

Related

How to pass data from model to controller (CodeIgniter, session help)

First sorry for my english( it is not my main language ).
I am new in CodeIgniter3 and i like it.
Lets say this is my model:
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
foreach ($query->result() as $row) {
$data['zamestnanec'] = $row->tpred_zamestnanci." ".$row->meno_zamestnanci. " ".$row->priezvisko_zamestnanci." ".$row->tza_zamestnanci;;
}
return ($data);
}
And this is my controller:
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno);
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}
I want to ask you how to pass/display data from model to session. To $this->session->userdata('user').
Can you explain me the correct process off passing data from model to controller and from model to session. (like if you were trying to explain to a man who is thinking slowly).
I do not want links to documentation, just one or few persons who can explain it on example.
you can pass information from model to controller in two ways.
By using session
first fetch information using query and return that array to controller.
it is good if you return data to controller first then in controller
set up the session by using that returned array.
As in this example.
Model
function login($uname, $upassword)
{
$this->db->select("*");
$tthis->db->from("table_name")
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
// you can user result_array() to get all information in array form.
$this->result = $query->result_array();
return $this->result;
}
In Controller
//Funkcia na prihlásenie používatela
function loginUser()
{
//Načítať model
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
if ($this->user_model->login($uname, $upassword))
{
$this->session->set_userdata('user', $meno); // here you are setting up the session.
$data['user'] = $this->session->userdata('user');
redirect('/otk/', $data);
}
else
{
redirect('/user/');
}
}
Hope this will help you :
get all the user information (in array) from the model whatever you want :
In controller :
First way :
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$lname = $this->input->post('lname');//example
$session_arr['uname'] = $uname;
$session_arr['fullname'] = $fname.' '.$lname; // example
$this->session->set_userdata($session_arr);
Second way :
$user = $this->user_model->login($uname, $upassword);
if ($user != false)
{
// Valid user
// $validate containing user details too. to check add this next line
// print_r($validate);die;
$this->session->set_userdata($user);
redirect('/otk/');
}
for more : https://codeigniter.com/user_guide/libraries/sessions.html#initializing-a-session
$user = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($user);
Just pass the model to controller whether data is correct or not. no need a big loop there in the model
In Model
function login($uname, $upassword)
{
$this->db->where('uname', $uname);
$this->db->where('upassword', $upassword);
$query = $this->db->get('zamestnanci');
$result = $query->result_array();
$count = count($result); # get how many data passed
if ($count == 1) {
return $result;
}
else
{
return false;
}
}
In Controller
function loginUser()
$this->load->model('user_model');
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
//$meno = $this->user_model->login($uname, $upassword);
//Ak sa meno a heslo zhoduje
$validate = $this->user_model->login($uname, $upassword);
if ($validate != false)
{
# Valid user
# $validate conating user details too. to check add this next line print_r($validate);die;
$this->session->set_userdata('user', $uname);
redirect('/otk/');
}
else
{
# Invalid User
redirect('/user/');
}
}
And in otk function just call session value user

Error trying to fetch data from 2 tables codeigniter

I gotta fetch data from 2 tables.. My tables are "Study","Users" and "Subjects"
"Study" includes:(id, user_id[is the foreign key to the column "id" of the table "Users"], subject_id[is the foreign key to the column "id" of the table "Subjects"], grade, date)
"Users" includes:(id,username,name,lastname,password,type,status,date)
"Subjects" includes:(id, career_id, name, description, hours)
I wanna get something like this at the end:
I got this errors:
Here is my code:
My view file ("home"):
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2 align="center">TABLE:Study</h2>
<input id="busqueda_tabla" type="text">
<table class="table table-hover" align="center" border="1" cellspacing="0" cellpadding="0" width="700" id="tabla_busqueda">
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
<th>Action</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['user']."</td>
<td>".$record['subject']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
<td align='center'>
<button type='button' class='btn btn-primary'>EDITAR</button></a> |
<button type='button' class='btn btn-danger'>BORRAR</button></a>
</tr>";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Here is my Controller file ("Home"):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
$data[$key]['user_id'] = $user[0]['username'];
$data[$key]['subject_id'] = $subject[0]['name'];
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
And my Model file ("Crudmodel"):
<?php
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM Study");
$result = $query->result_array();
return $result;
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
$result = $query->result_array();
return $result;
}
function getSubName($subject)
{
$query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
$result = $query->result_array();
return $result;
}
}
?>
Hope you can help me :/
Iam changed your query to join query, Simply change your code to below
public function index(){
# get all data in Study table
$query = $this->db->query("SELECT sd.user_id as id,sd.grade as grade,sd.date as date,sd.subject_id as subject,ur.username as user FROM Study as sd,Users as ur,Subjects as sb WHERE ur.id=sd.user_id and sb.id=sd.subject_id");
$result = $query->result_array();
$data['records'] = $result;
$this->load->view('home', $data);
}
and now run the code
Undefined indexes and trying to get property non-object more or less means the same thing which is you are not getting proper data or the variables or indexes you are trying to get are not initialized or undefined and cause of this can be error in query or blank data return by query you are running.
i would like to request you to pull your query data like this
$check = $this->db->query("SELECT * FROM SOMETHING AND YOUR CONDITION AND STUFF HERE");
if($check->num_rows()>0){
$result = $check->result();
return $result;
}else{
return false; // or anything you want.
}
let say this query function is stored in model and you are calling your model like this
$someVariable = $this->model_name->function();
if($someVariable!==FALSE){
// handle
}else
{
// handle
}
in the end, not sure why, but i also counter problems with double quotes sometime, YES I KNOW.. variable inside double quotes work, I'm just saying sometime... at least it happens with me, so i would like to request last thing. try debugging your query like this, currently you have
"SELECT * FROM TABLE WHERE THIS = $THAT"
Change this to
"SELECT * FROM TABLE WHERE THIS = '".$THAT."'"
I hope it will work out for you!.
EDITED:
(Sorry that i failed to show example from your own code)
Your Model file
<?php
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM Study");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getSubName($subject)
{
$query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function CombineResults($subject, $name){
// you can also use this
$query = $this->db->query("SELECT sub.name, user.username FROM Subjects sub, Users user WHERE sub.id=$subject AND user.id = $name");
if($query->num_rows()>0){
return $query->result();
}else{
return "";
// or anything you can use as error handler
}
}
}
?>
Your controller file
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
// we have condition on this model method/function we can validate
// response comming from this method and add handler just like we did
// for queries. your main problem can be this
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}

Fetch data from database in codeigniter

I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code
Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$data);
}
1) to fetch the entire data from a table in codeigniter
Model Code
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->result();
}
View Code
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
2) to fetch number of rows from a table in codeigniter
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
return $query->num_rows();
}
View Code
echo $instant_req;
You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records
for example in the model
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$result=$query->result();
$num_rows=$query->num_rows();
$last_three_record=array_slice($result,-3,3,true);
return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}
in controller dashboard function
public function dashboard()
{
$result = $this->admin_model->getreq();
$this->load->view('admin/dashboard',$result);
}
in view
foreach ($all_data as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//latest three record
foreach ($last_three as $perreq)
{
echo $perreq->fullname;
echo "<br>";
}
//total count
echo $num_rows;
Raw query may work here.
$resultSet = $this->db->query("select * from table_name");
$queryCount = count($resultSet );
Try this logic :
Model code :
public function getreq()
{
$this->db->where('status','pending');
$this->db->order_by('id', 'DESC'); //actual field name of id
$query=$this->db->get('instanthire');
return $query->result();
}
Controller Code :
public function dashboard()
{
$data['instant_req'] = $this->admin_model->getreq();
$data['total_record'] = count($data['instant_req']);
$this->load->view('admin/dashboard',$data);
}
View Code:
$i=0;
foreach ($instant_req as $perreq)
{
if($i<3){
echo $perreq->fullname;
echo "<br>";
}
$i++;
}
Echo 'Total record : '.$total_record;
Function
function getData($limit = 0){
//Create empty array
$data = [];
//Where clause
$this->db->where('status','pending');
//Order Data based on latest ID
$this->db->order_by('id', 'DESC');
if($limit != 0){
$this->db->limit($limit);
}
//Get the Data
$query = $this->db->get('instanthire');
$data['count'] = $query->num_rows();
$data['result'] = $query->result();
return $data;
}
Calls
//Last 3 Inserted
$data = getData(3);
//All Data
$data = getData();
CodeIgniter Database Documentation
Here is a simple solution that I can first think of but if you want me to maybe improve I can.
Just stick with your first code(Model) and in the view count how many items are iterated through.
$count = 0;
foreach ($instant_req as $perreq)
{
echo $perreq->fullname;
echo "<br>";
$count++;
}
echo $count;
Am I still missing something? just let me know
EDIT:
This is another solution, return an array
public function getreq()
{
$this->db->where('status','pending');
$query=$this->db->get('instanthire');
$data['results'] = $query->result();
$data['count'] = $query->num_rows();
return $data
}
I'm not very confident and haven't really tried this but on top of my head I think it can work.
Model:
public function getreq()
{
$res = $this->db->order_by("<place column primary id>","desc")->get_where('instanthire',['status'=> 'pending']);
$latest_3 = [];
if(count($res)){
$i=1;
foreach($res as $r){
$latest_3[]=$r;
if($i == 3)
break;
$i++;
}
}
$arr = [
'latest_3' => $latest_3,
'count' => count($res),
'total_result' => $res,
];
return $arr;
}

generating querying result for row() in codeigniter:

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

get query results from cdbcommand Yii

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

Categories