CodeIgniter View page is empty - php

First of all, I am absolutely new to CodeIgniter.
I'm trying to develop a simple CRUD page using CodeIgniter. So far, I've just created the View page, without any CRUD feature. It's just a normal view page, with a table that contains my model data retrieved from the database.
Here is the code for my view page which works ok, file name - show_users.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI CRUD</title>
</head>
<body>
<h2> Simple CI CRUD Application </h2>
<table width="600" border="1" cellpadding="5">
<tr>
<th scope="col">Id</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile</th>
<th scope="col">Address</th>
</tr>
<?php foreach ($user_list as $u_key){ ?>
<tr>
<td><?php echo $u_key->id; ?></td>
<td><?php echo $u_key->name; ?></td>
<td><?php echo $u_key->email; ?></td>
<td><?php echo $u_key->address; ?></td>
<td><?php echo $u_key->mobile; ?></td>
</tr>
<?php }?>
</table>
</body>
</html>
My model is - users_model.php
<?php
class Users_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database();
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
}
?>
My controller is - users.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
function __construct()
{
parent::__construct();
#$this->load->helper('url');
$this->load->model('users_model');
}
public function index()
{
$data['user_list'] = $this->users_model->get_all_users();
$this->load->view('show_users', $data);
}
}
?>
My database server is MySQL, database name ci_test and my table is users:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(255) NOT NULL,
`mobile` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
)
My view page is showing this output:
So far so good. Now, whenever I try to modify my view page show_users.php, the page is loaded, but empty.
Here is the code of my modified view page, for which I encounter the above mentioned problem:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CI CRUD</title>
<script type="text/javascript">
function show_confirm(act,gotoid)
{
if(act=="edit")
var r=confirm("Do you really want to edit?");
else
var r=confirm("Do you really want to delete?");
if (r==true)
{
window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;
}
}
</script>
</head>
<body>
<h2> Simple CI CRUD Application </h2>
<table width="600" border="1" cellpadding="5">
<tr>
<th scope="col">Id</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th scope="col">Mobile</th>
<th scope="col">Address</th>
<th scope="col" colspan="2">Action</th>
</tr>
<?php foreach ($user_list as $u_key){ ?>
<tr>
<td><?php echo $u_key->id; ?></td>
<td><?php echo $u_key->name; ?></td>
<td><?php echo $u_key->email; ?></td>
<td><?php echo $u_key->address; ?></td>
<td><?php echo $u_key->mobile; ?></td>
<td width="40" align="left" >Edit</td>
<td width="40" align="left" >Delete </td>
</tr>
<?php }?>
<tr>
<td colspan="7" align="right"> Insert New User</td>
</tr>
</table>
</body>
</html>
Note that I haven't changed anything in my model and controller yet.
Can anyone please specify where the problem is? Any convenient and efficient solution to this? I am using Notepad++ for development, no IDE.
EDIT: Although I found a solution to my problem and accepted it as answer, I'm still confused about one issue.
In my model - users_model.php, I have a line:
$this->load->database();
But in the tutorial, it was written like this:
$this->load->database("ci_test");
So basically, I forgot to provide my database name, which is ci_test. I still haven't edited my model code, but my view page is working perfectly now. So what is the significance of it? Is it necessary to mention the database name inside $this->load->database() ? Is this one of the reasons my view page was empty?

This is not the problem with your view page.
go to config folder open autoload.php
$autoload['helper'] = array('url');
Other Way
Uncomment the #$this->load->helper('url'); to $this->load->helper('url');
<?php
class Users_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function get_all_users()
{
$query = $this->db->get('users');
return $query->result();
}
}
?>

The answer for your comment : $this->load->database()
There are two ways to connect to a database:
The "auto connect" in application/config/autoload.php
$autoload['libraries'] = array('database');
Manually Connecting
The first parameter of this function can optionally be used to specify a particular database group from your config file, or you can even submit connection values for a database that is not specified in your config file.
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);

Instead of this <?php echo base_url();?>index.php/user/add_form
Use: <?php echo site_url('user/add_form');?>

I think problem is in this line:
window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;
maybe you have forgot load helper url?

Related

How to show array data form controller in blade file (html table)? Laravel

Since I am completely new in Laravel, I have a problem pretty complicated for me.
I have controller file ApiHandlerController like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Client;
class ApiHandlerController extends Controller
{
//
public function index()
{
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://jsonplaceholder.typicode.com/todos',
]);
$response = $client->request('GET', '/todos');
//get status code using $response->getStatusCode();
$body = $response->getBody();
$arr_body = json_decode($body);
return view('myview', $arr_body);
}
}
?>
myview.blade.php as a view file:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Todo</title>
<link rel="shortcut icon" type="image/x-icon" href="icon.ico">
<meta name="description" content="HTML, PHP, JSON, REST API">
<style>table, th, td {border: 1px solid black;}</style>
</head>
<body>
<table style="width:100%"; class="data-table">
<tr>
<th>User ID:</th>
<th>ID:</th>
<th>Title:</th>
<th>Completed</th>
</tr>
<?php foreach ($arr_body as $value) { ?>
<tr>
<td><?php echo $value -> userId ?> </td>
<td><?php echo $value -> id ?> </td>
<td><?php echo $value -> title ?> </td>
<td><?php echo $value -> completed ?> </td>
</tr>
<?php } ?>
</table>
And web.php file with route:
Route::get('myview', function () {
return view('myview');
});
My question is:
How to show result of todos from jsonplaceholder.typicode.com in this blade (view) file?
Currently, it's not possible, and every time I try this is an error:
ErrorException
Undefined variable: arr_body (View: C:\xampp\htdocs\TodoList\resources\views\myview.blade.php)
Thank you guys in advance!
To show array type data in blade...
First edit your controller code.
From:
return view('myview', $arr_body);
To:
return view('myview')->with('arr_body', $arr_body);
Below is core php syntex.
<td><?php echo $value['userId'] ?> </td>
Laravel syntex
<td>{{$value['userId']}}</td>
Hope this will be useful.

Pagination without LIMIT

Few weaks ago I started learning PHP and MVC. So I started making simple project and got stuck at pagination problem.. I need help to find the best solution for pagination in my website. In the most pagination examples I have found, pagination is made with SQL SELECT LIMIT, but in my case it seems not very logical.
I have BooksController:
<?php
require 'Database/Connection.php';
require 'Database/QueryBuilder.php';
require 'Database/Book.php';
class BooksController
{
public function index()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$books = $books->selectAll('books_table');
require 'views/listofbooks.view.php';
}
public function about()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$bookId = $_REQUEST['id'];
$book = $books->selectByID('books_table', $bookId);
require 'views/aboutbook.view.php';
}
public function search()
{
$config = require 'config.php';
$books = new QueryBuilder(Connection::make($config['database']));
$text = $_REQUEST['search'];
$books = $books->search('books_table', $text);
require 'views/listofbooks.view.php';
}
}
And ListOfBooks View:
<!DOCTYPE html>
<html>
<head>
<title>Books</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script src="styles/sorttable.js"></script>
<script>sorttable.sort_alpha = function(a,b) { return a[0].localeCompare(b[0], 'lt'); }</script>
</head>
<body>
<form action="/search" name="search" method="GET">
<input type="text" id="textbox" size="30" name="search" placeholder="Text" required />
<input type="submit" id="button">
</form>
<table class="sortable">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Year</th>
<th scope="col">Author</th>
<th scope="col">Genre</th>
</tr>
</thead>
<tbody>
<?php foreach($books as $book) : ?>
<tr>
<td data-label="Title"><?php echo $book->Title; ?></td>
<td data-label="Year"><?php echo $book->Year; ?></td>
<td data-label="Author(s)"><?php echo $book->Author; ?></td>
<td data-label="Genre"><?php echo $book->Genre; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
Should I change my recreate my BooksController or there is any other solution?
As you haven't mentioned that it has to be done in PHP, in my opinion, the easiest solution to your problem is a simple DataTable plugin. It is javascript (jQuery to be exact, but that is a javascript framework) and it will ease the usage of your server (there will not be one query for each of pagination pages, but one query and javascript will take care of pagination), but increase the use of client's PC. Also, you have filtering, search etc. available for dataTables, but here is the easiest to start with: https://datatables.net/examples/basic_init/zero_configuration.html

ERR_CONNECTION_REFUSED in CodeIgniter's Tutorial

I have good command over core PHP, and I have just started learning CodeIgniter. I have created some pages according to the CodeIgniter's Tutorial. But I am stuck in this tutorial: http://www.codeigniter.com/user_guide/tutorial/news_section.html
Following is the code:
/application/config/routes.php :
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['users/(:any)'] = 'users/view/$1';
$route['users'] = 'users';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
/application/models/Users_model.php :
class Users_model extends CI_Model
{ public function __construct()
{ $this->load->database();
}
public function get_users($username = FALSE)
{ if ($username === FALSE)
{ $query = $this->db->get('users');
return $query->result_array();
}
$query = $this->db->get_where('users', array('username' => $username));
return $query->row_array();
}
}
/application/controllers/Users.php :
class Users extends CI_Controller
{ public function __construct()
{ parent::__construct();
$this->load->model('users_model');
$this->load->helper('url_helper');
}
public function index()
{ $data['users'] = $this->users_model->get_users();
$data['title'] = 'List of Users';
$this->load->view('templates/header', $data);
$this->load->view('users/index', $data);
$this->load->view('templates/footer');
}
public function view($username = NULL)
{ $data['user'] = $this->users_model->get_users($username);
if (empty($data['user']))
{ show_404();
}
$data['title'] = $data['user']['display_name'];
$this->load->view('templates/header', $data);
$this->load->view('users/view', $data);
$this->load->view('templates/footer');
}
}
/application/views/users/index.php :
<div class='main'>
<table border='1'>
<tr>
<th>Name</th>
<th>Email Address</th>
<th>Username</th>
</tr>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['display_name'] ?></td>
<td><?php echo $user['email'] ?></td>
<td>#<?php echo $user['username'] ?></td>
</tr>
<?php } ?>
</table>
</div>
/application/views/users/view.php :
<h2><?php $user['display_name'] ?></h2>
<p>#<?php $user['username'] ?></p>
MySQL 'users' table's structure :
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255),
username VARCHAR(255),
display_name VARCHAR(50)
);
(You can replace .... (4 dots) with your desired domain name OR localhost in the below code.)
Output of ..../index.php/users page :
<html>
<head>
<title>List of Users</title>
</head>
<body>
<h1>List of Users</h1>
<div class='main'>
<table border='1'>
<tr>
<th>Name</th>
<th>Email Address</th>
<th>Username</th>
</tr>
<tr>
<td>Nikunj Bhatt</td>
<td>nikunj#example.com</td>
<td>#NikunjBhatt</td>
</tr>
</table>
</div>
</body>
</html>
This output is proper, but when I click on the username, it is redirecting to ..../index.php/users/NikunjBhatt page and this page is showing the error "This webpage is not available" "ERR_CONNECTION_REFUSED" in Google Chrome.
So, where is the problem? What I am missing?
Try to write code as below:-
public function view($username = ""){
// do your stuff here
}

How to correctly pass objects from the controller to the view in PHP?

For learning purposes, I built a very simple MVC-pattern. In order learn how to display the content of a specific database table in the view, I wrote a simple read-function in my model (m_crud.php) as so:
<?php
class Crud{
private $Database;
private $db_table = 'products';
function __construct()
{
global $Database;
$this->Database = $Database;
}
// READ (SELECT)
public function read(){
$query="SELECT * FROM $this->db_table";
$result= $this->Database->query($query);
$num_result=$result->num_rows;
if($num_result>0){
while($rows=$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
}
The database details are stored in init.php, where the CRUD-object is initiated as well:
<?php
// Connect to database
$server = 'localhost';
$user = 'root';
$pass = 'MyPassword';
$db = 'MyDatabase;
$Database = new mysqli($server, $user, $pass, $db);
// Error reporting
mysqli_report(MYSQLI_REPORT_ERROR);
ini_set('display_errors', 1);
// Include objects
include('app/models/m_crud.php');
include('app/models/m_template.php');
// Create Objects
$Crud = new Crud(); // Creates an instance of the CRUD Class
// Start session
session_start();
My controller (that's the part where I am stuck) looks as follows:
<?php
include('app/init.php');
$Template->load('app/views/v_members.php');
$obj = $Crud->read();
if ( ! empty($obj))
{
// Pass product data to view
// How do you correctly pass the object data to the view?
}
At the moment, I instantiate the CRUD-object within the view to display the content ofy my 'products'-table, which works, but effectively breaks the MVC pattern:
<?php include("includes/private_header.php"); ?>
<div id="content">
<?php
$obj=new Crud;
$obj->read();
?>
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">ID</th>
<td width="95">Category</td>
<td width="95">Name</td>
<td width="140">Description</td>
<td width="104">Price</td>
<td width="71">Image</td>
<td>action</td>
</tr>
<?php
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $category_id; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $price; ?></td>
<td><?php echo $image; ?></td>
<td>edit|Delete</td>
</tr>
<?php
}
?>
</table>
</div>
<?php include("includes/private_footer.php"); ?>
How can I pass the CRUD-object from controller to the view in order to clean up the view?
Set the variables echoed in your view in the if block of your controller. Assuming that "$Template->load('app/views/v_members.php');" calls your view, you then place that after the if block. Otherwise, you could include your controller at the top of your view script.
$obj = $Crud->read();
if ( ! empty($obj))
{
foreach($obj->data as $val){
extract($val);
}
}
//If your Template->load function is calling the view
$Template->load('app/views/v_members.php');

how to display content from database in codeigniter without calling controller from view?

I am new to codeigniter. I followed a video tutorial and successfully created a login registration system. After registration or login the users reach a page called members.php.
members.php is a view.
my controller is main.php and model is model-users.php.
I want members.php to show/have content from the database so that the users can read it once the login or register?
I followed a few resources on the web that said not to call controller from view. How can I accomplice the above without doing so?
Thanks
I think the CodeIgniter documentation is actually very clear, and very easy to follow. Nevertheless, here's an example of how you might structure your app.
Controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Members extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('members_model');
}
function index() {
$data['members'] = $this->members_model->get_members();
$this->load->view('header', $data);
$this->load->view('members');
$this->load->view('footer');
}
}
Model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Members_model extends CI_Model {
function get_members() {
$query = $this->db->get('members');
return $query->result_array();
}
}
View:
<?php
print_r($members);
To access the above page, you would visit http://yoursite.com/index.php/members.
You can use a .htaccess file to remove the index.php segment from the URI. The index() method is automatically called when you run a controller.
I don't have any example of the code, but I write one simple example of HTML when you can show name and surname of members.
Controller:
function members(){
$members = $this->model-user->get_list(); //array of members
$this->load->view('members.php', $members); // load members in view
}
View members.php
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
<?php foreach($members as $m): ?>
<tr>
<tr><?php echo $m['name']; ?>
<tr><?php echo $m['surname']; ?>
</tr>
<?php endforeach; ?>
<table>
</body>
</html>
Model:
function get_list() {
// query in database
return $query = $this->db->get('members'); //table name members
}
This is the simple example in a short form. I hope that you will understand it.
I think i know what you mean, this is definitely not the right way to go about this but if you really must you could call a model from a view like this.
In the view
<div>
<?php
#You could load the model here or autoload it in config->autoload->models(i believe)
$data = $this->model_name->model_function();?>
foreach($data as $row):
echo '<pre>';
print_r($row);
echo '</pre>';
endforeach;
?>
</div>
here is the example of my codes:
views:
<?php foreach($ecms as $i){ ?>
<tr>
<td><?php echo $i->accnum; ?></td>
<td><?php echo $i->crdnum; ?></td>
<td><?php echo $i->fname; ?></td>
<td><?php echo $i->bday; ?></td>
</tr>
<?php } ?>
model:
function masterHide()
{
$sql =" select * from ecms";
$query = $this->db->query($sql);
return($query->num_rows() > 0) ? $query->result(): NULL;
}
controller:
function search() {
// $this->MasterListAccess();
$this->load->model('navi_model');
$query = $this->navi_model->masterHide();
//check results or returned value of model
//print_r($query);
$data['ecms'] = $query;
$data['main_content'] = 'search';
$this->load->view('includes/template',$data);
}
At first connect the database in your project file and connect the model page in your view page and try this code.
Go to the view page and try this code
View
20
21
<?php
$get_data=$this->MyModel->get_table_data();
?>
<table class="table table-bordered">
<thead>
<tr>
<th> Name </th>
<th> Email </th>
<th> Phone No </th>
</tr>
</thead>
<tbody>
<?php foreach($get_data as $val){ ?>
<tr>
<td><?php echo $val->name; ?></td>
<td><?php echo $val->email; ?></td>
<td><?php echo $val->phone; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Model
public function get_table_data(){ $qry=$this->db->select('*')->from('Table Name')->get()->result(); return $qry; }

Categories