I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.
I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.
Any idea how I can get this to work? Code below.
Controller
function displayMovies() {
$this->load->model('movie_list_model');
$data['movielist'] = $this->movie_list_model->getList();
$this->load->view('movielist_view', $data);
}
Model
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row)
{
echo $row['firstname'];
echo $row['lastname'];
echo $row['favorite_movie'];
}
}
View
<?php foreach($movielist as $mlist)
{
echo $mlist->firstname . '<br />';
echo $mlist->lastname . '<br />';
echo $mlist->favorite_movie;
}
?>
If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.
A safety would be including something like this in your view:
if($movielist)
{
/* foreach() {} */
}
Also, your model should only return data (not echo it).
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result(); /* returns an object */
// Alternatively:
// return $query->result_array(); /* returns an array */
}
I also recommend using Active record:
function getList() {
$this->db->select('firstname');
$this->db->select('lastname');
$this->db->select('favorite_movie');
$query = $this->get('movies');
return $query->result();
}
Good luck!
Related
I have two list-filtering inputs, if used individually they work perfectly but when used together it returns an empty object.
the filters contain one simple search Input field, and one select.
they trigger an API call to the server which when used both looks like this
http://127.0.0.1:8000/api/user?&search=jom&type=admin
the method which this call trigger looks like this
public function index(Request $request) {
$search = $request->input('search');
$type = $request->input('type');
$user = User::select('*');
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
...
the method checkSearch looks like this
private function checkSearch(&$query, $search) {
if (!isset($query)) {
return $query;
}
if (!is_null($search)) {
$searchTerms = $this->stringToArray($search, ' ');
$query = $query->where(function ($query) use ($searchTerms) {
for ($i = 0, $max = count($searchTerms); $i < $max; $i++) {
$term = str_replace('_', '\_', mb_strtolower('%' . $searchTerms[$i] . '%'));
$query->whereRaw("(Lower(name) LIKE ?)", [$term, $term])
->orWhereRaw("(Lower(bio) LIKE ?)", [$term, $term]);
}
});
}
}
and the filterUserType like this
private function filterUserType(&$query, $type) {
if (!isset($query)) { return $query; }
if (!is_null($type)) {
$query = $query->where( 'type', $type);
}
}
I've tried to check the where on the filterUserType method, to orWhere but this just returns values of both not combined.
I triggered a break on the raw query and it appeared like this
select * from `users` where ((Lower(name) LIKE %jom%) or (Lower(bio) LIKE %jom%)) and `type` = %jom%)
When I switched the methods I got the right results.
Switching from
$this->checkSearch($user, $search); // check for search
$this->filterUserType($user, $type); // filter user type
to
$this->filterUserType($user, $type); // filter user type
$this->checkSearch($user, $search); // check for search
Still don't know why but it worked
I have a problem with my code, the first code is like
<?php
require_once('zend/json.php');
require_once('zend/db.php');
//require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>'localhost',
'username'=>'stet',
'password'=>'test',
'dbname'=>'test'
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from info ";
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
and it works well, but I want to make it like
<?php
include ('table.php');
include ('config.php');
require_once('zend/json.php');
require_once('zend/db.php');
require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>$dbhost,
'username'=>$dbuser,
'password'=>$dbpass,
'dbname'=>$dbdb
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from ".$table;
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
I don't know whats wrong with this code, I need help.
the error message Notice: Undefined variable: dbdb in C:\wamp....
The config.php is only have code like $dbpass = 'test'; and like that, I'm creating a simple web and I want to make my code to other database and aplikasi, so I only changed the config.php and the table.php
for the table.php maybe will work if the config.php work.
Thanks.
You are using a class and not paying attention to variable scope.
I understand you have variables with values for the DB connection in that config.php file. Although these variables are available inside the script file with the include they are NOT available and accessible inside your class. The only difference would be any constants with define (or variables inside a global which is not a good idea).
You could create a config class inside the config.php and set the values as properties then instantiate that class inside your _koneksi method. And then you would use a require_once instead of the include.
UPDATE
So here's an example that is similar to your file where your include ('config.php'); is essentially the same as declaring your variables directly before the class begins.
// variable defined outside the class
$foo = 'foo';
class demo
{
public $bar = 'bar';
function test()
{
$foobar = 'foobar';
echo 'Class property $bar is:' . $this->bar . PHP_EOL;
echo 'Local variable $foobar is:' . $foobar . PHP_EOL;
}
function run()
{
if (isset($foo)) {
echo 'Global variable $foo is:' . $foo . PHP_EOL;
} else {
// This is where you have your problem.
// Variables from outside the class are not available.
echo 'Global variable $foo not found' . PHP_EOL;
}
}
}
$demo = new demo();
$demo->test(); // Class property $bar is:bar
// Local variable $foobar is:foobar
$demo->run(); // Global variable $foo not found
echo 'Variable $foo is: ' . $foo . PHP_EOL; // Class property $bar is:bar
I have 2 tables:
Events and Registration.
Events Fields: EventID and EventName
Registration Field: MemberID and Name
I want to pull the EventName and the Name- of the person. How do I do this with a model?
The code I have:
Model
function getAll()
{
$query = $this->db->get('tblRegistration');
if( $query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
return $data;
}
controller
public function getallevents() {
$this->load->model('events_model');
$data['records'] = $this->events_model->getAll();
$this->load->view('view-events', $data);
}
View
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->Name</td>";
// echo "<td> $row->intLocationID</td>";
echo "</tr>";
endforeach;
Edit
OK I have added the data that I want out of the table.
model
function getAll()
{
// get all the records from the schools table
$this->db->select('*');
$this->db->from('tblRegistration as reg');
$this->db->join('tblMeetRace as met', 'reg.intMeetRaceID = met.intEventID');
$query = $this->db->get();
// if the number of rows returned is more than 0
if( $query->num_rows() > 0) {
// loop through each record (row) and place that
// record into an array called $data
foreach ($query->result() as $row) {
$data[] = $row;
}
}
$query->free_result();
// return the array to the controller
return $data;
}
view
foreach ($records as $row):
echo "<tr>";
echo "<td> $row->intMeetRaceID/td>";
echo "<td> $row->intEventID</td>";
echo "</tr>";
endforeach;
but I get an error of:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/view-events.php
Line Number: 89
First of all you need to add another column in your events table for storing the MemberId, say memberid.
Once you have that, when ever a member registers for an event, you can store his ID in the events table and relate it.
Then you can use Joins to fetch the datas
$this->db->select('*');
$this->db->from('registration as reg');
$this->db->join('events as evt', 'reg.id = evt.memberid');
$query = $this->db->get();
I'm extracting two different sets of data from a function in my model (syntax below). I'm trying to display the data my view. I put the variable in var_dump and var_dump is displaying the requested information but I'm having a hard time accessing that information. I'm getting two different sets of error messages as well. They are below. How would I display the information in my view? Thanks everyone.
Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
Model_data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
View
<?php
var_dump($allvehicledata).'<br>';
//print_r($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo "Cities of " . $allvehicledata->cardescription_id . "<br />";
$id = $allvehicledata['getPrice']->id;
$model = $allvehicledata[0]->model;
$make = $allvehicledata->make;
echo "$id".'<br>';
echo "$make".'<br>';
echo "$model".'<br>';
echo $allvehicledata->year;
}
?>
Error Messages
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 7
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 9
In your controller you are assigning the result of function getJoinInformation to the variable allvehicledata. This variable is then assigned to the view.
The function getJoinInformation is returning an array with the following
$data = array(
'getPrice' => $this->getPrice($year,$make,$model),
'getOtherPrice' => $this->getOtherPrice($year,$make,$model)
);
So in your view you can access the attributes getPrice and getOtherPrice in the object $allvehicledata like
$allvehicledata->getPrice;
$allvehicledata->getOtherPrice;
In line 7 you try to access the attribute cardescription_id, which is not an attribute of the object $allvehicledata.
I think this is an attribute which is get from the db query, so you should try to access it allvehicledata->getPrice->cardescription_id or allvehicledata->getOtherPrice->cardescription_id.
In line 9 you try to access some data stored in an array $model = $allvehicledata[0]->model;, but $allvehicledata is not an array.
I currently have a report that give me the users ID number and their email address, But I would like to make this in a CSV file instead of tables and rows like I currently have.
Here is my controller
function View_Email_E()
{
$data = array();
if($query = $this->report_model->View_Email_English())
{
$data['records'] = $query;
}
$data['main_content'] = 'view_all_email_english';
$this->load->view('includes/template', $data);
}
Here is my model
function View_Email_English()
{
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '#');
$query = $this->db->get('Membership');
return $query->result();
}
For some reason my view is not being shown in code mode, but it is an auto generated table using these this snippet of code. Each row returns ID and Email from the database.
<?php if(isset($records)) : foreach($records as $row) : ?>
How can I make a CSV file with just ID and email fields?
Thanks
I think you can use the csv_from_result function in dbutil to do it. Try something like this:
$csvContent = $this->dbutil->csv_from_result($query);
if ( ! write_file('./path/to/file.csv', $csvContent)) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
http://codeigniter.com/user_guide/database/utilities.html#csv
Add
$this->db->select(array('ID','Email'));
To your View_Email_English function.