codeigniter数据库代码无法正常工作

时间:2013-03-04 06:18:12

标签: php database codeigniter

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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,结果显示为$result

相关问题