I am trying to get two values 'total number of movies' and 'details of movies' from database.
For total number of movies, i am returning with php error "undefined_index:num_films".
please help me.
Sakila_control
<?php
class Sakila_control extends CI_Controller
{
function display($offset=0)
{
$limit = 20;
$this->load->model('films_model');
$result = $this->films_model->search($limit,$offset);
$data['films']=$result['rows'];
$data['num_results']=$result['num_films'];
$this->load->view('films_view',$data);
}
}
Films_model
<?php
class Films_model extends CI_Model
{
function search($limit,$offset)
{
$qu = $this->
db->select('FID,title,description,category,price,length,rating,actors')
->from('film_list')
->limit($limit,$offset);
//rows comes from controller
$ret['rows']= $qu->get()->result();
return $ret;
$q = $this->db->select(`COUNT(*) as count`, FALSE)
->from('film_list');
//num_rows comes from controller
$tmp= $q->get()->result();
$ret['num_films']=$tmp[0]->count;
return $ret;
}
}
Films_view
<body>
<table>
<div>
Found <?php echo $num_results;?> Films
</div>
<thead>
<th>ID</th>
<th>Title</th>
<th>description</th>
<th>category</th>
<th>price</th>
<th>length</th>
</thead>
<tbody>
<?php
foreach($films as $film):?>
<tr>
<td><?php echo $film->FID;?> </td>
<td><?php echo $film->title;?></td>
<!-- <td><?php echo $film->description;?></td> -->
<td><?php echo $film->category;?></td>
<td><?php echo $film->price;?></td>
<td><?php echo $film->length;?></td>
<td><?php echo $film->rating;?></td>
<!-- <td><?php echo $film->actors;?></td> -->
</tr>
<?php endforeach;?>
</tbody>
</table>
</body>
</html>
First you will need to comment out this:
// return $ret;
Then, you need to fix another error with backticks that you didn't get yet because of the return statement...
Backticks in PHP will attempt to run code from the command line.
Change this:
$q = $this->db->select(`COUNT(*) as count`, FALSE)
To this:
$q = $this->db->select('COUNT(*) as count', FALSE)
Final result:
<?php
class Films_model extends CI_Model
{
function search($limit,$offset)
{
$qu = $this->
db->select('FID,title,description,category,price,length,rating,actors')
->from('film_list')
->limit($limit,$offset);
//rows comes from controller
$ret['rows']= $qu->get()->result();
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('film_list');
//num_rows comes from controller
$tmp= $q->get()->result();
$ret['num_films']=$tmp[0]->count;
return $ret;
}
}
Read more on backticks here: http://php.net/manual/en/language.operators.execution.php
Execution Operators
PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
According to your code you are returning the value just after the first query. So your function is not returning the num_films.
class Films_model extends CI_Model
{
function search($limit,$offset)
{
$qu = $this->
db->select('FID,title,description,category,price,length,rating,actors')
->from('film_list')
->limit($limit,$offset);
//rows comes from controller
$ret['rows']= $qu->get()->result();
// return $ret;
$q = $this->db->select('COUNT(*) as count`, FALSE)
->from('film_list');
//num_rows comes from controller
$tmp= $q->get()->result();
$ret['num_films']=$tmp[0]->count;
return $ret;
}
}
Check multiple return in same function
What about this
In Model
class Films_model extends CI_Model
{
function search($limit,$offset)
{
# Just pass all data to controller
$query = $this->db->query("SELECT * FROM film_list LIMIT $limit, $offset");
$result = $query->result_array(); # Changed
return $result;
}
}
In Controller
class Sakila_control extends CI_Controller
{
function display()
{
$limit = 20;
$offset=0
$this->load->model('films_model');
$data['films'] = $this->films_model->search($limit,$offset);
$count = count($data['films']); # get count on here
$data['num_results'] = $count;
$this->load->view('films_view',$data);
}
}
In View
All Fine and its up to you
Related
I want to create a loop for my database result. But I can't make it work on my VIEW file.
So here's my model:
<?php class Dash_model extends CI_Model {
public function __construct()
{
parent::__construct();
// Loading second db and running query.
$CI = &get_instance();
//setting the second parameter to TRUE (Boolean) the function will return the database object.
$this->db2 = $CI->load->database('db2', TRUE);
}
public function query0()
{
$query = $this->db2->query("SELECT name FROM table1 ORDER BY date");
return ($query->result());
}
public function query1()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query2()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query3()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query4()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
}
Let's say that my query works ok, I've tested it on my SQL Server. And then here's my CONTROLLER:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dash_control extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('dash_model');
$this->load->library('table');
}
public function index()
{
$tmpl = array (
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
);
$this->table->set_template($tmpl);
$data['result0'] = $this->dash_model->query0();
$data['result1'] = $this->dash_model->query1();
$data['result2'] = $this->dash_model->query2();
$data['result3'] = $this->dash_model->query3();
$data['result4'] = $this->dash_model->query4();
$this->load->view('dashboard',$data);
}
}
So i have 5 function in my model, the result was supposed to be a LOOP data. After I put the model inside my CONTROLLER, I pass it to my VIEW file like this:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction Success</th>
<th>Transaction Failure</th>
<th>Total Visit</th>
<th>Total Item</th>
</tr>
</thead>
<tbody>
<?php foreach (array_combine($result0, $result1, $result2, $result3, $result4) as $row)
{ ?>
<tr>
<td><?php echo $row->queryalias0; ?></td>
<td><?php echo $row->queryalias1; ?></td>
<td><?php echo $row->queryalias2; ?></td>
<td><?php echo $row->queryalias3; ?></td>
<td><?php echo $row->queryalias4; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
The error I got was:
Message: array_combine(): Both parameters should have an equal number of elements
And:
Message: Invalid argument supplied for foreach()
The result that I would like to achieve should be like this:
Thank you guys, for all your help...
From php.net
array_combine — Creates an array by using one array for keys and
another for its values
array array_combine ( array $keys , array $values )
You using wrong way array_combine function. You can try array_merge instead
foreach (array_merge($result0, $result1, $result2, $result3, $result4) as $row)
This is my model
<?php
class home_model extends CI_Model {
function login()
{
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0)
{
foreach ($q->result() as $row)
{
$data[]['username'] = $row->username;
$data[]['email'] = $row->email;
$data[]['sex'] = $row->sex;
$data[]['dob'] = $row->dob;
$data[]['mobile'] = $row->mobile;
}
return $data;
}
?>
This is my controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class home extends CI_Controller
{
public function index()
{
$this->load->model('home_model');
$data['records'] = $this->home_model->login();
$this->load->view('home', $data);
}
}
I am only able to print_r and that is not how i want it, how will i echo this? I don't know what format I should use in my echo,
echo($records[0]);
This format is what I tried but it returns the error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/home.php
Line Number: 4 Array
How should I code my view?
first of all your login function is need to corrected as per codeigniter.
function login() {
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0) {
return $q->result_array();
}
it will provide an array as you required.
then to use in views, you need to use it following.
suppose you want to echo first user name
echo $records[0]['username'];
Here $records[0] is an array and hence you need to use as above mention and similarly for other field.
Use following process
Your Modal
function login()
{
$q = $this->db->query('SELECT * FROM users');
$count = $q->num_rows();
if ($count > 0)
{
return $q->result();
}
}
?>
No change for controller
On View
foreach ($records as $row)
{
$username = $row->username;
$email = $row->email;
$sex = $row->sex;
$dob = $row->dob;
$mobile = $row->mobile;
}
In your views
foreach($records as $users)
{
echo $users['username'];
}
Use the builtin function print_r() and provide the array is an argument
I have MVC on CI that not show error but cant get the result.
This the Script
Controller
customer.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customer extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('customer_view');
}
function tampil_customer()
{
$this->load->model('customer_model');
$data = array('tests' => $this->customer_model->tampil_data_customer());
$this->load->view('customer_view', $data);
}//end fucnntion
}//end class
?>
Model
customer_model.php
<?php
class Customer_model extends CI_Models
{
public function tampil_data_customer()
{
$results = array();
$this->db->select('*');
$this->db->from('customer');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
}
?>
View
customer_view.php
<table border="1" align="center" widht="900">
<tr>
<td colspan="5" align="center"><h2>Data Customer</h2></td>
</tr>
<tr>
<th>Nama</th>
<th>Company</th>
<th>Alamat</th>
<th>Telepon</th>
<th>HP</th>
</tr>
<?php
//$result = $this->result();
if( !empty($results) )
{
foreach($results as $isi)
{
echo "<tr>";
echo "<td>$isi->nama</td>";
echo "<td>$isi->company</td>";
echo "<td>$isi->alamat</td>";
echo "<td>$isi->telepon</td>";
echo "<td>$isi->hp</td>";
//echo anchor('customer/edit_customer/'.$isi->ID, 'Edit')."|";
//echo anchor('customer/hapus_customer/'.$isi->ID, 'Hapus')."|";
echo "</tr>";
}
}
?>
</table>
the Result only show the HTML like this
Can Anyone Help me to Fix this Problem?
Im very new Using CodeIgniter. I never use Framework before.
Im very appreciated your Answer.
Thanks
You are storing the result from database to array tests here
$data['tests'] = $this->customer_model->tampil_data_customer();
and trying to call it in view with an undefined array $results.
Try with this.
if(!empty($tests->result())){
foreach($tests->result() as $isi)
{
echo "<tr>";
echo "<td>".$isi->nama."</td>";
echo "<td>".$isi->company."</td>";
echo "<td>".$isi->alamat."</td>";
echo "<td>".$isi->telepon."</td>";
echo "<td>".$isi->hp."</td>";
echo "</tr>";
}
}
In model can you make it simple like this,
public function tampil_data_customer()
{
$query=$this->db->query('select * from customer');
$results = $query->result();
return $results;
}
when you pass in arguments using $this->load->view() function,you are using the view() function with the instance of Loader load,it's in /system/core/Loader.php. As the block comments say
An associative array of data to be extracted for use in the view.
if you pass in an object,you can get the public properties by simply using the property name,you can't get the protected and private property.
if you pass in an Multi-dimensional Array,you can get the value by using key/keys in the Multi-dimensional Array.
By the way,you must pass in an array or object other a variable.
sample below
model.php(application\models\test)
class model extends CI_Model {
public $ss=1;
protected $bb=1;
private $vv=3;
}
controller.php(application\controllers)
class Hello extends CI_Controller
public function __construct() {
parent::__construct ();
}
public function index() {
$this->load->model('test/model');
$model=new model();
$this->load->view ( 'test/view', $model );
}
view.php(application\views\test)
echo $ss;
then you get the value of object.
CONTROLLER FUNCTION
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
$table = $this->table->generate($query);
return $table; //Added this
}
Calling in another function:
$questionstable = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
VIEW CODE:
<table>
<thead>
<th>Question Id</th>
<th>Question Name</th>
<th>Survey Id</th>
<th>Created On</th>
</thead>
<tbody>
<?php foreach ($questionstable as $questionrow) ?>
<tr>
<td><?php $questionrow -> QuestionId;?></td>
<td><?php $questionrow ->Name;?></td>
<td><?php $questionrow ->SurveyId;?></td>
<td><?php $questionrow ->CreatedOn;?></td>
</tr>
<?phpendforeach;?>
</tbody>
</table>
I am unable to access the array variable please help someone do i need a model can i work without it?
It should be
return $table; //good
and not
return; $table; //bad
You don't need the ; after return unless you want to return nothing.
In your calling function, do this too:
$questionstable['dataquestions'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
You're referring to $dataquestions in your view, but that variable doesn't exist.
Also, in your foreach, you're missing the : at the end.
It should be:
foreach($dataquestions as $questionsrow):
try this
first load this
$this->load->library('table');
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
return $query->result_array();
}
$questionstable = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
in view just use this
echo $this->table->generate($questionstable);
no foreach needed for more info check this
http://ellislab.com/codeigniter/user-guide/libraries/table.html
Try with this :
In Controller return the query object
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
return $query; //Added this
}
In other function, try like
$data['questionstable'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $data);
and in view fetch details like
<?php foreach ($questionstable->result() as $questionrow) ?>
<tr>
<td><?php echo $questionrow -> QuestionId;?></td>
<td><?php echo $questionrow ->Name;?></td>
<td><?php echo $questionrow ->SurveyId;?></td>
<td><?php echo $questionrow ->CreatedOn;?></td>
</tr>
<?php endforeach;?>
I think you forgot to write little code:Change below line with your line in public function displayallquestionsandoptions() {} method
$table = $query->result_array();
and little change In your calling another function line...
$data['questionstable'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $data);
how can I show all the users in the users table in the database in a html table?
I have to show all the users in a html table and each user can be selected using a check box. The selected users are then deleted from the database.
I am using the technique mvc and I have a page "DeleteUser" that contains only the html, a controller and a public file.
View/DeleteUser.php contains:
<form method="post" action="../public/deleteUser.php">
<table>
<tr>
<td>#</td>
<td>Username</td>
<td>First name</td>
<td>Last name</td>
<td>City</td>
<td>Gender</td>
<td>E-mail</td>
<td>Check</td>
</tr>
<tr>
<td><input type="submit" name="submit-deleteuser" value="Delete user"/></td>
</tr>
</table>
</form>
public/deleteUser.php contains:
$controller = new DeleteUserController();
$view = $controller->invoke();
$view->render();
The invoke() method in Controller/DeleteUserController.php contains:
class DeleteUserController {
public $user;
public $users;
public $userRepository;
public $view;
public function __construct() {
$username = $_SESSION['username'];
$this->userRepository = new UserRepository();
$this->user = $this->userRepository->findByUsername($username);
$this->users = array();
$this->view = new View('DeleteUser');
$db = Database::getInstance();
}
public function listUsers() {
$this->users = $this->userRepository->fetchAll();
foreach($this->users as $u) {
$str = "<tr>
<td><?php $u->getId() ?></td>
</tr>";
}
}
public function deleteUsers() {
if(isset($_POST['submit-deleteuser'])) {
$del_id = $_POST['users'];
foreach($del_id as $value) {
$value->delete();
}
}
}
public function work() {
$this->listUsers();
$this->deleteUsers();
}
public function invoke() {
$this->work();
$this->view->setData('user', $this->user);
return $this->view;
}
If I had not had to use mvc I would have done so:
<table>
<tr>
<td>#</td>
<td>Username</td>
<td>Fisrt name</td>
<td>Last name</td>
<td>City</td>
<td>Gender</td>
<td>E-mail</td>
<td>Check</td>
</tr>
<?php
$utente = $_SESSION['username'];
$query = "SELECT * FROM users ORDER BY id";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo "<tr>
<td>$row[id]</td>
<td>$row[username]</td>
<td>$row[fisrt_name]</td>
<td>$row[last_name]</td>
<td>$row[city]</td>
<td>$row[gender]</td>
<td>$row[email]</td>
<td><input type=\"checkbox\" name=\"users[]\" value=\"" .$row['id']. "\"></td>
</tr>";
}
}
?>
<tr>
<td colspan="9"><input type="submit" name="submit-deleteuser" value="Delete users"/></td>
</tr>
</table>
But now I do not know how to do. The two methods listUsers() and deleteUsers() are wrong and do not know how to complete them or correct them.
First it was simple, I put the php code that showed users in the html tag that I wanted (<table>...</table>) but now?
I do not know how to handle this thing.
Give me advice? Thank you :)
fetchAll() is:
public function fetchAll(){
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM `users`");
$stmt->execute();
$users = array();
while($result = $stmt->fetch()) {
$users[] = User::load($result);
}
return $users;
}
The attempt to use the MVC pattern is admirable, but a little bit off in this case :). What is missing, is the concept of controller actions.
Maybe try to restructure your code something like this:
Directory Structure
controllers/
UsersController.php
models/
UsersModel.php
core
View.php
views/
header.tpl.php
footer.tpl.php
users/
list.tpl.php
delete.tpl.php
users.php
1. Start with a users model that interacts with the database
class UsersModel {
public function fetchAll() {
$result = array();
// Build SELECT query, fetch all users from db., and store in $result
// ...
return $result;
}
public function deleteMany(array $ids) {
$result = array();
// Build DELETE query, execute it, and store the number of affected records in $result
// ...
return $result;
}
}
2. Make a UsersController instead of a DeleteUserController. Create two methods: listUsersAction and deleteUsersAction.
class UsersController {
public function listUsersAction() {
$model = new UsersModel();
$data = $model->fetchAll();
return new View(
'users/list',
$data
);
}
public function deleteUsersAction() {
// This is simplistic, but the idea is to get the required input from the request (and actually validate it!)
// Also see the users/list template further down
$ids = $_POST['user_ids'];
$model = new UsersModel();
$numRecords = $model->deleteMany($ids);
return new View(
'users/delete',
array('deleted_records' => $numRecords)
);
}
}
3. Our View class should store the template name and the view data, and be able to render the template
class View {
public static $viewDirectory;
public $template;
public $data = array();
public function __construct($template, $data) {
if (!View::$viewDirectory) {
View::$viewDirectory = dirname(__FILE__) . '/views/';
}
$this->template = $template;
$this->data = $data;
}
public function render() {
// Make the data available in the template
$data = $this->data;
// Include the template.
require(realpath(View::$viewDirectory . $this->template . '.tpl.php'));
}
}
4. The users/list template could then look something like this
// views/users/list.tpl.php
<form action="/users.php?action=delete" method="post">
<?php foreach ($data as $user): ?>
<div>
<input type="checkbox" name="user_ids[<?= $user['id'] ?>]" value="1"/>
<?= $user['username'] ?>
</div>
<?php endforeach; ?>
</form>
5. Tie everything together in users.php
<?php
// users.php
// (include all previously defined classes here)
// We'll want to include a HTML header of some sort:
include("views/header.tpl.php");
/**********
* Poor man's routing; valid urls:
* /users.php?action=listUsers
* /users.php?action=deleteUsers with POST data
*/
// Determine the action from the GET parameter. If no action is set, the default action is listUsers
//$action = (array_key_exists('action', $_GET) ? $_GET['action'] : 'listUsers');
// Equivalent of:
if (array_key_exists('action', $_GET)) {
$action = $_GET['action'];
} else {
$action = 'listUsers';
}
//--
$actionMethod = $action . 'Action';
$controller = new UsersController();
if (method_exists($controller, $actionMethod)) {
$view = $controller->$actionMethod();
$view->render();
} else {
echo "<div class='error'>The action '$action' is invalid for the Users controller.'</div>";
}
// We'll want to include a footer as well:
include("views/footer.tpl.php");
?>