foreach not working in codeigniter - php

I am currently new to database query and other for codeigniter can not seem to quite get model working for what I am after.
I have tried loading db in direct to controller and that works OK. But if I call my model does not want to work nothing shows up.
Here is what I would like to achieve.
Controller
public function website_test_model() {
$this->load->model('admin/website/model_website');
$results = $this->model_website->getWebsites();
$data['websites'] = array();
foreach ($results as $result) {
$data['websites'] = array(
'website_id' => $result['website_id'],
'name' => $result['name'],
'url' => $result['url']
);
}
$this->load->view('website/websites', $data);
}
View
<!-- Not Working From Controller Function Model Test -->
<?php if ($websites) { ?>
<?php foreach ($websites as $website) { ?>
<?php echo $website['website_id'];?>
<br>
<?php echo $website['name'];?>
<br>
<?php echo $website['url'];?>
<?php } ?>
<?php } ?>
Model
<?php
class Model_website extends CI_Model {
function getWebsites() {
$this->db->select('*');
$this->db->from('website');
$this->db->where('website_id');
$this->db->where('name');
$this->db->where('url');
$query = $this->db->get();
if($query->num_rows() > 0) {
return $query->row();
} else {
return false;
}
}
}
Codeigniter Demo It works when I try it this way as said on codeigniter User Guide. Just the code above is way I am after though Trying to make model work no luck
public function website() {
$results = $this->db->get('website'); // Works Direct From Controller OK.
foreach ($results->result() as $row) {
$data = array(
'website_id' => $row->website_id,
'name' => $row->name,
'url' => $row->url
);
}
$this->load->view('website/website', $data);
}

you are doing wrong in you model file
<?php
class Model_website extends CI_Model {
function getWebsites() {
$query =$this->db->get('website');
if($query->num_rows() > 0) {
return $query->result();
}
}
}
1) In your model you are using where condition but $this->db->where('website_id'); but you not passing anything in your condition you have to do like this $this->db->where('website_id',$yourwebsite_id);

You have to check db query in model it's return result or not.
use this query in model
$this->db->last_query();

Use this query in model
$query = $this->db->get('website');
return $query;
Pass this query to view then use this foreach
foreach ($query->result() as $row)
{
<?php echo $row->website_id; ?>
<br>
<?php echo $row->name;?>
<br>
<?php echo $row->url;?>
}

Related

Select and display all rows in Codeigniter

I'm novice in Codeigniter framework and I want to ask if is good or it exist another method to display all rows from database in view page.
I have this controller:
class Dashboard extends CI_Controller{
public function index()
{
$data['user'] = $this->dashboard_model->get_user_details($this->session->userdata('logged_in'));
$this->load->view('includes/header', $data);
Model dashboard:
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
$this->db->select("*");
$this->db->where('id', $user_id);
$result = $this->db->get('users');
return $result->result_array ();
}
}
And I display in view page like:
<?php echo $user[0]['id']; ?>
<?php echo $user[0]['username']; ?>
Code is working, it show me what I want but I don't know if this is a good solution.
You can also use return $result->row_array (); if it returns only single row.
and then in your view file get the data by using : $user['id'];
for multiple rows :
your solution is fine but you need to add foreach loop and get the data
ex:
foreach($user as $usr) {
echo $usr['id']; echo "<br/>";
echo $usr['username'];
}
By applying $this->db->where('id', $user_id); you will only get results (1) for the user with $user_id (not all users) and (2) you will only get results if a user with that id exists in the database. The correct way to get all users, while slightly modifying your function to support returning only one user is as follows:
/**
* #param int $user_id When NULL will return all users
* #return array
*/
public function get_user_details($user_id = null) {
$this->db->from('users');
if (!is_null($user_id)) {
$this->db->where('id', $user_id);
$q = $this->db->get();
if ($q->num_rows() !== 1) {
return array();
}
return $q->row_array();
} else {
return $this->db->get()->result_array();
}
}
So to get all users: $this->dashboard_model->get_user_details()
To get logged in user: $this->dashboard_model->get_user_details($this->session->userdata('logged_in'))
To get a user with id 123: $this->dashboard_model->get_user_details('123')
When $user_id is blank you can go through results like:
if (count($users) !== 0) {
foreach ($users as $user) {
echo $user['id'];
echo $user['username'];
}
} else {
echo 'No users';
}
When $user_id is set you get a single result thus this will work:
if (count($users) !== 0) {
echo $users['id'];
echo $users['username'];
} else {
echo 'User with that id does not exist!';
}
For single user information I would use row_array() or row()
https://www.codeigniter.com/userguide3/database/queries.html
<?php
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
$this->db->where('id', $user_id);
$result = $this->db->get('users');
return $result->row_array();
}
}
Controller
<?php
class Dashboard extends CI_Controller {
public function index()
{
$this->load->model('dashboard_model');
// Use the users id stored in your session when logged in
$userinfo = $this->dashboard_model->get_user_details($this->session->userdata('id'));
$data['id'] = $userinfo['id'];
$data['username'] = $userinfo['username'];
$this->load->view('includes/header', $data);
}
}
Then echo on view
<?php echo $username;?> example <?php echo $id;?>
Updated answer : As per details provided in commnets
instead of return $result->result_array(); use return $result->row_array();
View :
<?php echo $user['id']; ?>
<?php echo $user['username']; ?>
For fetching multiple rows :
return $result->result_array(); will give you array of all the users present in users table.
What you need to do is, access those users in view page using foreach loop.
<?php
foreach ($user as $row) {
echo $row['id'];
echo $row['username'];
}
?>
In your MODEL
class Dashboard_model extends CI_Model{
public function get_user_details($user_id){
return this->db->get_where('users', array('id' => $user_id))->result_array(); //You can use result_array() for more than one row and row_array() only for one row
//If you want to show all rows form database use this return $this->db->get('users')->result(); OR result_array()
}
}
In your View
For more than one row use foreach loop
foreach($user as $usr){
echo $usr['']; //Add all your database data here like this
}

How to use two tables data in a view in Codeigniter

I have two tables, first table is about topic name and second table shows sub-topics. I want to show from first table topic name then search their corresponding sub-topic and show it in view and so on till topic names are found in first table. But the problem is i can only get one table data in view i.e. main topic table. I have no idea how to get full data of both table and use it.
Database Structure:
Model:
<?php
class Topics_Model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_all_topics()
{
$this->load->database();
$this->db->select("*");
$this->db->from("topics");
$query=$this->db->get();
return $query->result();
}
}
?>
Controller :
<?php
class drag_drop_course_material extends CI_Controller {
function drag_drop_course_material()
{
parent::__construct();
}
function index()
{
$this->load->model('topics_model');
$data['query']=$this->topics_model->get_all_topics();
$this->load->helper('url');
$this->load->view('drag_drop_course_material', $data);
}
}
?>
View:
<?php
foreach ($query as $row) {
?>
<li> $row->topic_name </li>
<? } ?>
Required Output:
Try this query. We do left join of both tables.
$CI->db->select('*');
$CI->db->from('topic');
$CI->db->join('sub-topics', 'topic.id = sub-topics.sub_topic_id', 'left');
$query = $CI->db->get();
$result = $query->result();
You will get result in your model. return this result from model and access it in controller. Once you print return result in controller you will get idea that how to render it because you already did it above.
Your controller is perfect, your model is perfect just change your view:
In view:
foreach ($query as $row)
{ ?>
<ul>
<li><?php echo $row['topic_name'];?>
<ul>
<?php $this->db->where('sub_topic_id',$row['id'])
$r = $this->db->get('subtopics');
if($r->num_rows()>0)
{
foreach ($r -> result_array() as $row) {
$data1[] = $row;
}
}
foreach($data1 as $sub){?>
//print <li><?php echo $sub['subtopic_name']?></li>
<? }?>
</ul>
</li>
<? }?>
</ul>

displaying data in table using codeigniter

table is not displaying any value in table. When i did var_dump($results). It printed NULL. Since, i am new to codeigniter, i am not able to solve this problem.
I'm not getting, where i did mistake. Help Me.
View Page
<tbody>
<?php
if(!empty($results) ) {
foreach($results as $row) {
echo '<tr>';
echo '<td>'." ".'</td>';
echo '<td>'.$row->FileTitle.'</td>';
echo '<td>'.$row->UploadedFile.'</td>';
echo '<td>'.$row->CreationDate.'</td>';
echo '<td>'.$row->UpdateDate.'</td>';
echo '<td>'." ".'</td>';
echo '</tr>';
}
}?>
</tbody>
Controller
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function member_CAttachments()
{
$data['results'] = $this->news_model->member_MAttachments();
$this->load->view('member/templates/header');
$this->load->view('member/index',$data);
$this->load->view('member/templates/footer');
}
}
Model
class News_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function member_MAttachments()
{
$results = array();
$query = $this->db->get('MemberFileDetails');
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
}
Instead you can do it in fewer lines with inbuilt CI Table library,
supports both 2.2 and 3.x versions.
Use it like,
$this->load->library('table');
$this->table->set_heading('FileTitle', 'UploadedFile', 'CreationDate', 'UpdateDate');
$query = $this->db->query('SELECT * FROM MemberFileDetails');
echo $this->table->generate($query);
do you have records in your table ? if yes then please try to remove the
if($query->num_rows() > 0) condition in the model and try.
remove $results = array(); in your code

REST app + codeigniter + database

I did a REST app + codeigniter + database following: https://github.com/chriskacerguis/codeigniter-restserver , works perfect, wonderful.
Right now my json file getting static data, how can i get data from database?
i wrote a file and i can get from database the data, but i have no idea how to get the data from database in json, can you guys help me? thank you.
That file return to me that static json, works perfect, I would like get data from database.
/controllers/hello.php
<?php
include (APPPATH.'/libraries/REST_Controller.php');
class Hello extends REST_Controller {
function world_get(){
$data = new stdClass();
$data->name = 'Mark ';
$this->response($data, 200);
}
}
These files below I can get data from database but in html, how can I get data in json format?
/controllers/site.php
<?php
Class Site extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function index(){
$this->load->model('data_model');
$data['rows'] = $this->data_model->getAll();
$this->load->view('home', $data);
}
}
/models/data_model.php
<?php
class Data_model extends CI_Model {
function getAll(){
$q = $this->db->query("SELECT * from data");
if($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data [] = $row;
}
return $data;
}
}
}
views/home.php
<htmL>
<body>
<pre>
<?php foreach ($rows as $r)
{
echo '<h1>' . $r->title . '</h1>';
}
?>
</pre>
<?php foreach ($rows as $r) : ?>
<h1> <?php echo $r->author; ?></h1>
<h1> <?php echo $r->contents; ?></h1>
<?php endforeach; ?>
</body>
</htmL>
You are making API.To return data you don't need to call view.You can do it simply this way
function index()
{
$this->load->model('data_model');
$data = $this->data_model->getAll();
$this->response($data, 200);
}
Your model function is OK but you can make it simple.
function getAll()
{
return $this->db->get('data')->result();
}
just use json_encode in your controller and little change in your model file
Controller
function index(){
$this->load->model('data_model');
$result= $this->data_model->getAll();// change this line
$data['rows']= json_encode($result);// add this line
$this->load->view('home', $data);
}
Model
<?php
class Data_model extends CI_Model {
function getAll(){
$q = $this->db->query("SELECT * from data");
if($q->num_rows() > 0) {
return $q->result();
}else{
return false;
}
}
}

Codeigniter undefined variable: title , PHP error is encountered

I'm working on simple application consisting of simple form. My code really works fine in local environment. But when i uploaded it on a live server gives an error, unable to fetch database fields and i think there is an error in my model.
Here is my model class
class Model_get extends CI_Model
{
function getData($page) {
$query = $this->db->get_where('ci_tbl', array('page' => $page));
print_r($query->result());
return $query->result();
}
}
Here goes my view
<div id="content">
<?php
foreach ($results as $row) {
$title = $row->title;
$para1 = $row->para1;
$para2 = $row->para2;
}
echo heading($title, 1);
?>
<p><?php echo $title;?></p>
<p><?php echo $para1;?></p>
<p><?php echo $para2;?></p>
</div>
My controller goes as
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index()
{
$this->home();
}
public function home() {
$this->load->model('model_get');
$data['results'] = $this->model_get->getData('home');
$this->load->view('header');
$this->load->view('nav');
$this->load->view('main_content',$data);
$this->load->view('footer');
}
public function about() {
$this->load->model('model_get');
$data['results'] = $this->model_get->getData('about');
$this->load->view('header');
$this->load->view('nav');
$this->load->view('about_page',$data);
$this->load->view('footer');
}
Make sure you actually return the results of the query:
//print_r($query->result());
return $query->result();
At the moment you've commented out return $query->result(); and you're just printing the result. The controller calling the model isn't going to get that information and therefore isn't passing through to the view.
Also check that the database connection is correct if moving from local to a public environment.
Actually you had an error
foreach ($results as $row) {
$title=$ row->title;
^^^^
It should be
$title = $row->title;
^^^
You need to update your query within model as
class Model_get extends CI_Model {
function getData($page) {
$query = $this - > db - > get_where('ci_tbl', array('page' => $page));
return $query->result_array();
}
}

Categories