CodeIgniter foreach - php

I am fairly new to CodeIgniter and I'm sure there's a simple answer. I need to determine if there are records returned prior to executing this line of code in my VIEW:
foreach ($announcements->result_array() as $announcement_data){
My disconnect is that I can't check if array is empty because it is not an array yet until the foreach line is executed. Checking if $announcements is empty also doesn't work.
CONTROLLER:
public function summary() {
$this->load->model('Propinfo_model');
$data['propid'] = "516";
$data['propinfo'] = $this->Propinfo_model->get_propinfo($data['propid']);
// query for proposal info
$data['announcements'] = $this->Propinfo_model->get_announcements($data['propid']);
$this->load->view('summary_view', $data);
}
MODEL:
// Select all records from 'prop_announcements' table per prop ID
public function get_announcements($propid) {
// Build query
$this->db->select('*');
$this->db->from('prop_announcements P');
$this->db->join('ssp_users', 'P.user = ssp_users.userid');
$this->db->where('P.propid', $propid);
return $this->db->get();
}
VIEW:
foreach ($announcements->result_array() as $announcement_data){
echo $announcement_data['user']; // example field
}

You use
if ($announcements->num_rows() == 0) {
//code for no rows
}
https://www.codeigniter.com/userguide3/database/results.html

Related

How to pass variables from controller to show their values in blade file

I want to show variables value in blade file. Below is the controller code:-
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with($select_clientlist);
}
else
{
return view('client-database')->withMessage('No Details Found');
}
}
I want to show the values coming in $select_clientlist variable. Below is the code in my blade file:-
#foreach($select_clientlist as $clientlist)
{{$clientlist->firstname}}
#endforeach
And below is the route file code:-
Route::post('client_list_ajax','ClientDatabase\ClientdatabaseController#ClientListReviews');
I am receiving error.
What am I doing wrong?
Pass the variable using compact method
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
view1,view2,view3 are variable names
Since you only pass the variable when there is records wrap your for each inside isset
if (isset($select_clientlist)) {
foreach($select_clientlist as $clientlist) {
}
}
your query should be like this . you may be forget SELECT statement
$select_clientlist = DB::table('users_booking')->select('*')->where('service_provider', '=', 1)->get();
Either use as
return view('client-database')->with('select_clientlist',$select_clientlist);
Or
return view('client-database',compact('select_clientlist'));
Also add in select_clientlist else part to prevent undefined error
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with('select_clientlist',$select_clientlist);
}
else
{
$select_clientlist = [];
return view('client-database')->with('select_clientlist',$select_clientlist)->withMessage('No Details Found');
}
}
OR check by isset($select_clientlist) in blade file
$__currentLoopData = isset($select_clientlist)?$select_clientlist:[];
Pass that variable to your view either way .. it should be a collection. If there are no records, it is just empty. The foreach wont run if its empty. Its as simple as that. No need to check if anything is set or is empty etc... just always pass that collection.
public function ClientListReviews()
{
$select_clientlist = DB::table('users_booking')->where('service_provider', 1)->get();
$view = view('client-database', compact('select_clientlist'));
if ($select_clientlist->isEmpty()) {
$view->with('message', 'No Details Found');
}
return $view;
}

Codeigniter not getting data though available in mysql database

I have a model which fetch the data from database is below
public function counselor() {
$inst_id = $this->session->userdata('user_id');
$submission_key=$this->session->userdata('submission_key');
$query = $this->db->query("SELECT * FROM counselor where USER_ID = $inst_id AND submission_key= $submission_key");
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}
}
I have tested the $inst_id and $submission_key by printing it and its set.
$inst_id=2 and $submission_key=2016-8 .BUT though I have one record in database with those two field set its not returning the data. What is the case. I have tried with codeigniter get() and where() method too. Still not giving me the result.
Just write your query using active record function. It will help you in escaping string
$this->db->select('*',FALSE);
$this->db->where('USER_ID',$inst_id);
$this->db->where('submission_key',$submission_key);
$query=$this->db->get('counselor');
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}

Codeigniter php MVC

I have a table called 'News' with three columns: 'id', 'title' and 'details'
I have a function ('get_entry') inside a codeigniter model class (called 'News_model')
function get_entry()
{
$this->load->database();
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
return $data['newsarray'];
}
I am connecting to the db so that is not the problem.I want to return an iterable array from get_entry() by calling the function from a controller file with the followlwing code. I want to push it into another array (called '$data['theNews']') using the code below.
foreach ($this->News_model->get_entry() as $key => $value){
array_push($data['theNews'],$value->title);
}
I have been using the code on this (https://www.codeigniter.com/user_guide/general/models.html) as a template (in particular the function 'get_last_ten_entries()' but I think I am close with the code I posted above. I would appreciate any help.
About your code:
You have two 'return' in your get_entry function:
function get_entry()
{
$this->load->database();
// First
return $this->db->select('id,title,details')->from ('news');
$data['newsarray'] = $this->db->row_array();
// Second
return $data['newsarray'];
}
Change it to:
function get_entry()
{
$this->load->database();
$query = $this->db->select('id,title,details')->from('news');
$data['newsarray'] = $query->row_array();
return $data['newsarray'];
}
It should work now.
Some advices:
Don't use Codeigniter 2 anymore. Version 3 is alive.
If you plan to return whole table columns, i suggest you to use the following code for the query:
$query = $this->db->get('news', 1, 20);
Where 1, 20 is the limit.
Now you can get the result:
return $query->result();
A simple example:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news', 1, 20);
return $query->result();
}
This method returns the query result as an array of objects that you can print like so in your controller:
$news_array = $this->News_model->get_entry();
foreach ($news_array as $news)
{
echo $news->id;
}
Look at CI 3 Query Builder query builder for more examples.
One more suggestion, just autoload the database library in application/config/autoload.php if you need it globally.
Changing the code to this in the function worked:
function get_entry()
{
$this->load->database();
$query = $this->db->get('news');
//return $query->result();
foreach ($query->result() as $row)
{
echo "</br>";
echo $row->id;
echo "</br>";
echo $row->title;
echo "</br>";
echo $row->details;
echo "</br>";
}
}
Calling the function like so prints it out:
$news_array = $this->News_model->get_entry();

How to search for multiple values in a single field of mysql table using codeigniter active record?

I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole

Returning and using multidimensional array of records from database in CodeIgniter 2.0

Hey guys !
Well I was trying out codeigniter but it seems to me that I have made some kind of mess while trying to retrieve and display the data from the tables
here is the code snippet.
I want to retrieve all the articles stored in my article table along with that I need to pull out all the tags associated with each article from the relationship table and the tag table called articleTagRelation and tags respectively
Table structure :
Article table : articleID, articleContent, date
Tags table : tagID, tagName
articleTagRelation : aricleID,tagID {Combination of both is my primary key}
CI model :
article_model.php
public function getAllTags($postId){
$this->db->select('articleTagRelation.tagId as tagId, articleTagRelation.postId as postId, article.tagName as tagName,');
$this->db->from('articleTagRelation');
$this->db->join('Tags','Tags.tagId = articleTagRelation.tagId');
$this->db->where('ArticleTagRelation.articleId',$postId);
$qTag = $this->db->get();
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
return $tag;
}
}
}
public function getAllArticles(){
$this->db->select('*');
$this->db->from('Article');
$this->db->order_by('date','desc');
$query=$this->db->get();
if($query->num_rows()>0){
foreach ($query->result() as $row) {
$data['row'] = $row;
$data['articletags'] = $this->getAllTags($row->articleId); // I'm trying to get get a array of all the associate tags.
$post=array($data['row'],$data['articletags']);
}
}else{
echo 'nothing found !';
}
return $post;
}
my controller file
article.php
I'm calling this function in the index function
$data['rows'] = $this->blog_model->getAllArticles();
and then loading the view by passing the data array
now the part where things get messy
in my view
echo $r->articleId // works fine
echo $r->articletags->tagId //gives me a error message
Can any one help me out in printing those tagIds
First you don't need the foreach at all to get the tag information, it comes back from a query_result.
like this...
if($qTag->num_rows() > 0){
return $qTag->result();
}
else {
return array(); //return empty array if no tags
}
Then to build your article, do this with getAllArticles()
public function getAllArticles(){
// removed uneccessary select and from
// the below accomplishes the same thing
$this->db->order_by('date','desc');
$query = $this->db->get('Article');
if ( $query->num_rows() > 0 ) {
// store the result in a variable you will end up returning
$articles = $query->result();
// make sure you foreach by reference so that changes you make
// to the interated $article will be made to the actual article
// result
foreach ($articles as &$article) {
// create a new property of your article "tags" and save an
// array of tags in it
$article->tags = $this->getAllTags( $article->articleId );
}
} else {
echo 'nothing found !';
}
return $articles;
}
The last thing to note is that when you now reference $r->tags that is an array, so you can foreach it to process all tags, OR reference an index like $r->tags[3]->tagId
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
$tags[] = $tag; //this create the array with the result
}
return $tags;
}
"$r->articletags->tagId" only works if you return results as an object, use "$r->articletags['tagId']" instead.

Categories