-2

我目前是 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);

表内容:

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

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

4

2 回答 2

1

问题是你没有返回任何东西。

$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阅读更多内容

http://ellislab.com/codeigniter/user-guide/database/results.html

于 2013-03-04T06:22:20.577 回答
0

在模型中使用这个:

$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 as$title和 result as$result

于 2013-03-04T06:31:31.113 回答