Here's my model:
<?php
class Dbtest extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function getAll() {
parent::Model();
$this->db->select('title, content');
$this->db->from('posts');
$this->db->where('post_id', 1);
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
}
Here's my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dbtest extends CI_Controller {
function index() {
$this->load->model('dbtest');
$data['rows'] = $this->dbtest->getAll();
$this->load->view('dbtest', $data);
}
}
And here's my view
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="container">
<p>My view has been loaded</p>
<?php foreach($rows as $r) : ?>
<h1&g开发者_Python百科t;<?php echo $r->title; ?></h1>
<div><?php echo $r->content; ?></div>
<?php endforeach; ?>
</div>
</body>
</html>
I keep getting a 500 server error. What could I possibly be doing wrong. I have autoloaded the database library. Please help a codeigniter newbie trying to learn this great framework.
function getAll() {
parent::Model(); //<-------------------Remove this line
$this->db->select('title, content');
$this->db->from('posts');
After taking a quick look, why is this line there?
It is a php4 constructor call to the old version of the Model base class that no longer exists..
remove and try again.
EDIT
Also, you cannot name a model AND Controller the same name, they have namespace conflicts.
call the model Dbtest_model
or something and use it that way.
Also, this is unnecessary
if($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
$q->result()
returns an array, no need to loop through and rebuild... Just do this...
if($q->num_rows() > 0) {
return $q->result();
}
Well after some pretty crappy stuff... I finally found that the problem was in my desition to put some Vars after the
class CI_model{}
in the Core Model (application/system/core/Model) of my CI application, just for the goods of autocompletion for Eclipse/aptana/netbeans. So if you can revert back to normal from a clean CI installation, i think it should get back to normal, this was my final solution. Happy Coding!
What happens if you call parent::CI_Model();
instead of parent::__construct();
?
Ci is designed to work on php4, and __construct()
wasn't added until php5.
精彩评论