Get object with index of object in list yii php - php

This is code query data from database :
public function getAllUser(){
$connect = Yii::app()->db;
$query = "SELECT * FROM user";
$statement = $connect->CreateCommand($query);
$result = $statement->query();
return $result;
}
After that I use Controller to get data & send to View :
public function actionIndex()
{
$consultas = new ConsultasDB();
$listUser = $consultas->getAllUser();
$this->render('index', array
("listUser" => $listUser));
}
In View I know show all information from database by loop listUser
foreach ($listUser->readAll() as $user)
{
echo 'Username : '.$user["username"].'<br>';
echo 'Password : '.$user["password"].'<br>';
}
but I don't know how to get a object with an index. Ex: User[1]...
Thanks!

Add this in your view, before the foreach loop
echo "<pre>";
print_r($listUser->readAll());
echo "</pre>";
Hope this helps you out.!

Related

i want to display value from database in codeigniter but i am getting errror

I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
controller:
public function trainer($id)
{
$user_record = $this->db->query("select * from usr_data where usr_id=$id")->result();
$data['title'] = 'trainer Dashboard';
$data['user_record'] = null;
$data['active_courses'] = [];
$data['inprogress'] = [];
if(count($user_record)) {
$user_record = $user_record[0];
$data['title'] = ucwords($user_record->firstname).' Dashboard';
$data['user_record'] = $user_record;
$active_courses = $this->base_model->getTrainercourseAll($id);
$data['active_courses'] = $active_courses;
$inprogress = $this->base_model->getstaffinprogress($id);
$data['inprogress'] = $inprogress;
}
$this->load->view('trainer-dashboard', $data);
}
model:
public function getstaffinprogress($user_id) {
$result=$this->executeSelectQuery("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
return $result;
}
view:
<h3>Avg inprogress:<?php echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";?></h3>
I want to display the column percentage which is coming from database.above code is in the controller, model and view.i thought my controller code is wrong.
Anyone help me to get rid of this error. I want to display a value in view in CodeIgniter but I am getting several errors like trying to get the property on non-object. I think my code is correct but I am getting errors. Below is my code.
Try this in your view file,
if(isset($inprogress)){
echo $inprogress->percentage;
}
Then your code look like this,
<h3>Avg inprogress:<?php if(isset($inprogress)){ echo "<span style='color:#ff00ff;font-family:verdana;'>".$inprogress->percentage."</span>";}?></h3>
Then call the controller function. I think inprogress is not set at the first time.
If it doesn't work, try to var_dump($inprogress) in controller and check value and type.
And try this code in your model. Query also seems not correct
public function getstaffinprogress($user_id) {
$this->db->select_avg('ut_lp_marks.percentage');
$this->db->where('ut_lp_marks.obj_id', $user_id);
$this->db->where('object_data.type', 'crs');
$this->db->where('ut_lp_marks.status', 1);
$this->db->join('object_data', 'object_data.obj_id = ut_lp_marks.obj_id');
$query = $this->db->get('ut_lp_marks');
return $query->result_array();
}
I assume that your db is ut_lp_marks. Then var_dump array and check data is correct first. Then access array element.
public function getstaffinprogress($user_id) {
$result = array();
$query=$this->db->query("select AVG(m.percentage) from object_data o, ut_lp_marks m where o.obj_id=m.obj_id and o.type='crs' and m.status=1 ");
foreach($query->result() as $row){
$result = $row;
}
return $result;
}
Also check $inprogress->percentage exists before print in view.

How to pass values from looping in controller to view using php codeigniter

I have a question, I don't know how to get multiple values from looping in controller to get the user's presence in each course. I want to show the user's presence in each course in view. Thank you very much.
This is my controller (MenteeController)
public function indexMentee(){
$this->load->model('UserModel');
$userID=$this->session->userdata('userID');
$groupID = $this->UserModel->getGroupID($userID);//to get user's groupID
$records = $this->UserModel->getGroupCourseLearned($groupID);//to get group's course learned
$data['courseID'] = $records['courseID'];
$data['countCourseID'] = $records['countCourseID'];
foreach($data['courseID'] as $d){
$data['present'] = $this->UserModel->totalPresentCourse($d->courseID,$userID);//total user's presence in certain course
}
$this->load->view('mentee/home',$data);
}
This is my model (UserModel)
public function getGroupID($userID){
$query = $this->db->query("SELECT DISTINCT groupID FROM mslearningsession WHERE menteeID='".$userID."'");
if($query->num_rows()>0){
return $query->row()->groupID;
}else{
return false;
}
}
public function getGroupCourseLearned($groupID){
$query = $this->db->query("SELECT DISTINCT courseID FROM mslearningsession WHERE groupID IN('".$groupID."')")->result();
return array(
'courseID' => $query,
'countCourseID' => count($query),
);
}
public function totalPresentCourse($courseID,$userID){
$query = $this->db->query("SELECT COUNT(sessionID)AS present FROM mslearningsession WHERE menteeID='".$userID."' AND courseID='".$courseID."'");
if($query->num_rows()>0){
return $query->row()->present;
}else{
return false;
}
}
This is my view (home.php)
<?php
echo "total courses learned : ".$countCourseID."<br>";//the courses are more than one
echo "total user's presence in each course :";
foreach($courseID as $course){
echo $course->courseID;
//I don't know how to get multiple values from looping in controller to get the user's presence in each course
}
?>
you can do it something like this
$data['new_array'] = array(); //declare an empty array first
foreach($data['courseID'] as $d){
$data['new_array'] = $this->UserModel->totalPresentCourse($d->courseID,$userID);//all the value will be pushed in to new array
}
$this->load->view('mentee/home',$data);//pass the array to get the data

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

Codeigniter form_helper getting database rows to be values in select menu

I am writing a form, which has a select menu in it, I want the values to pulled from the database, so I thought it would be something along these lines:
My view
<?php
echo form_open('admin/save_content');
echo form_fieldset();
echo form_dropdown('categories', $select_options);
echo form_submit('category_submit', 'Submit');
echo form_fieldset_close();
echo form_close();
?>
My controller
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$data['select_options'] = $this->category_model->get_all_online();
$this->load->view('admin/content/add_content', $data);
}
my model
public function get_all_online() {
$this->db->select('*');
$this->db->from('category');
$this->db->where('category_online', 1);
$query = $this->db->get();
return $query->result();
}
now when I place the $selected_options in the form dropdown I get this error,
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass
could not be converted to string
Filename: helpers/form_helper.php
Line Number: 331
You need to pass an array to your dropdown, where the array key will be the value that is POSTed and the value will the text that is displayed.
To achieve this, change your controller like so:
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$data['select_options'] = $this->category_model->get_all_online_select();
$this->load->view('admin/content/add_content', $data);
}
and add this function to your model
public function get_all_online_select() {
$this->db->select('id, name'); //change this to the two main values you want to use
$this->db->from('category');
$this->db->where('category_online', 1);
$query = $this->db->get();
foreach($query->result_array() as $row){
$data[$row['id']]=$row['name'];
}
return $data;
}
That should do the trick
I personally hate to make assumptions in my Models about how my data will be used as that is the job of the controller. If you add a MY_array_helper.php and paste this in:
function array_to_select() {
$args = func_get_args();
$return = array();
switch(count($args)):
case 3:
foreach ($args[0] as $itteration):
if(is_object($itteration)) $itteration = (array) $itteration;
$return[$itteration[$args[1]]] = $itteration[$args[2]];
endforeach;
break;
case 2:
foreach ($args[0] as $key => $itteration):
if(is_object($itteration)) $itteration = (array) $itteration;
$return[$key] = $itteration[$args[1]];
endforeach;
break;
case 1:
foreach ($args[0] as $itteration):
$return[$itteration] = $itteration;
endforeach;
break;
default:
return FALSE;
break;
endswitch;
return $return;
}
Then you can do something like this:
function add_content() {
$data = array();
$this->is_logged_in();
$this->load->model('category_model');
$this->load->helper('array');
$data['select_options'] = array_to_select($this->category_model->get_all_online(), 'id', 'title');
$this->load->view('admin/content/add_content', $data);
}
That supports multi-dimensional arrays by passing in one or two keys, or single dimensional arrays by using the value as the value and the key.
Eg: array_to_select(array('value1', 'value2')) gives array('value1'=>'value1', 'value2'=>'value2')
You need to return an array of strings, result() is an array of objects.
Maybe try this in your model:
return $query->result_array();
In your view, you can add foreach there instead of in Model.
<?php
echo form_open('admin/save_content');
echo form_fieldset();
foreach($select_options->result_array() as $row){
$data[$row['id']]=$row['name'];
echo form_dropdown('categories', $row);
}
echo form_submit('category_submit', 'Submit');
echo form_fieldset_close();
echo form_close();
?>
Not tested.
I have edited Phil Surgeon's array helper to work with a simple db query with only two fields (id & value). So the helper class now looks like this:
<?php
function array_to_select() {
//get args
$args = func_get_args();
//get args key names
$keys = array_keys($args[0][0]);
//set return array
$return = array();
foreach ($args[0] as $itteration){
//$itteration[$keys[0]] is field id value, $itteration[$keys[1]] is field name value
$return[$itteration[$keys[0]]] = $itteration[$keys[1]];
}
return $return;
}
And you can use it again in your controller.
Hope it's usefull.
form drop down with lot of options codeigniter form drop down menu with validation class also

Categories