编码器数据库代码不工作


codeigniter database code not working

我目前是CodeIgniter的初学者,我正试图获得一个简单的MVC数据库的东西来工作,但它不会。我试图从表中选择一条记录并将其显示到网页上,但我却出现了错误。我将把我的代码贴在下面,这样你就可以看到我在做什么:

模型:

function grabData() {
    $sql = "SELECT * FROM books WHERE id = 1";
    $config['hostname'] = "localhost";
    $config['username'] = "root";
    $config['password'] = "";
    $config['database'] = "bookstore";
    $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";
    // manually connect to database
    $this->load->database($config, TRUE);
    // do some stuff
    $query = $this->db->get('books');
    if ($query->num_rows() > 0) {
        return true;
    } else {
      return false;
    }

}

控制器:

$web['title'] = "CI Hello World App!";
$this->load->view('helloworld_view', $web);
$this->load->model('helloworld_model');
$data['result'] = $this->helloworld_model->grabData();
$this->load->view('helloworld_view', $data);

Table:

1     The Grapes of Wrath            John Steinbeck     12.99
2     Ninteen Eighty-Four            George Orwell      8.99
3     The Wind-Up Bird Chronicle     Haruki Murakami    7.99

错误:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: result
Filename: views/helloworld_view.php
Line Number: 8
null
boolean true

我没有显示视图,因为我觉得这不是问题的根源。任何帮助都会很感激。谢谢!

问题是您没有返回任何内容。

$query = $this->db->get('books');
if ($query->num_rows() > 0) {
    return true;
} else {
  return false;
}

你没有返回结果,这就是为什么结果在视图上是空的,

$query = $this->db->get('books');
if ($query->num_rows() > 0) {
    return $query->result(); // return a result() or row() or row_array()
} else {
  return false;
}

是一个简写版本return $query->num_rows() > 0 ? $query->result() : FALSE;此示例将返回

处的object read morehttp://ellislab.com/codeigniter/user-guide/database/results.html

在模型中使用:

$query = $this->db->get('books');
    if ($query->num_rows() > 0) {
        return $query->result_array();
    } else {
      return false;
    }

只在控制器加载视图中出现一次:

$data['title'] = "CI Hello World App!";
$this->load->model('helloworld_model');
$data['result'] = $this->helloworld_model->grabData();
$this->load->view('helloworld_view', $data);

因此,您可以访问标题为$title,结果为$result