目录

CodeIgniter - 使用数据库( Working with Database)

与任何其他框架一样,我们需要经常与数据库进行交互,CodeIgniter使我们的工作变得轻松。 它提供了丰富的功能,可以与数据库进行交互。

在本节中,我们将了解CRUD(创建,读取,更新,删除)函数如何与CodeIgniter一起使用。 我们将使用stud table来选择,更新,删除和插入stud表中的数据。

表名:螺柱
roll_noint(11)
namevarchar(30)

连接到数据库

我们可以通过以下两种方式连接到数据库 -

  • Automatic Connecting - 可以使用文件application/config/autoload.php完成自动连接。 自动连接将为每个页面加载数据库。 我们只需要添加数据库库,如下所示 -

$autoload['libraries'] = array(‘database’);
  • Manual Connecting - 如果只想要某些页面的数据库连接,那么我们可以进行手动连接。 我们可以通过在任何类中添加以下行来手动连接到数据库。

$this->load->database();

这里,我们没有传递任何参数,因为所有内容都在数据库配置文件application/config/database.php中设置

插入记录

要在数据库中插入记录,请使用insert()函数,如下表所示 -

Syntax

insert([ $table = '' [, $set = NULL [, $escape = NULL ]]])

Parameters

  • $tablestring ) - 表名

  • $setarray ) - 字段/值对的关联数组

  • $escapebool ) - 是否转义值和标识符

Returns

成功时为TRUE,失败时为FALSE

Return Type

bool

以下示例显示如何在stud表中插入记录。 $ data是一个数组,我们在其中设置数据并将此数据插入表stud ,我们只需要将此数组传递给第二个参数中的insert函数。

$data = array( 
   'roll_no' => ‘1’, 
   'name' => ‘Virat’ 
); 
$this->db->insert("stud", $data);

更新记录

要更新数据库中的记录, update()函数与set()where()函数一起使用,如下表所示。 set()函数将设置要更新的数据。

Syntax

set( $key [, $value = '' [, $escape = NULL ]])

Parameters

  • $keymixed ) - 字段名称或字段/值对的数组

  • $valuestring ) - 字段值,如果$ key是单个字段

  • $escapebool ) - 是否转义值和标识符

Returns

CI_DB_query_builder instance (method chaining)

Return Type

CI_DB_query_builder

where()函数将决定要更新的记录。

Syntax

where( $key [, $value = NULL [, $escape = NULL ]])

Parameters

  • $keymixed ) - 要比较的字段名称或关联数组

  • $valuemixed ) - 如果是单个键,则与此值相比较

  • $escapebool ) - 是否转义值和标识符

Returns

DB_query_builder instance

Return Type

object

最后, update()函数将更新数据库中的数据。

Syntax

update([ $table = '' [, $set = NULL [, $where = NULL[, $limit = NULL ]]]])

Parameters

  • $tablestring ) - 表名

  • $setarray ) - 字段/值对的关联数组

  • $wherestring ) - WHERE子句

  • $limitint ) - LIMIT子句

Returns

成功时为TRUE,失败时为FALSE

Return Type

bool
$data = array( 
   'roll_no' => ‘1’, 
   'name' => ‘Virat’ 
); 
$this->db->set($data); 
$this->db->where("roll_no", ‘1’); 
$this->db->update("stud", $data);

删除记录

要删除数据库中的记录,请使用delete()函数,如下表所示 -

Syntax

delete([ $table = '' [, $where = '' [, $limit = NULL[, $reset_data = TRUE ]]]])

Parameters

  • $tablemixed ) - 要删除的表格; 字符串或数组

  • $wherestring ) - WHERE子句

  • $limitint ) - LIMIT子句

  • $reset_databool ) - TRUE重置查询“write”子句

Returns

CI_DB_query_builder实例(方法链接)或失败时为FALSE

Return Type

mixed

使用以下代码删除stud表中的记录。 第一个参数表示要删除记录的表的名称,第二个参数决定要删除的记录。

$this->db->delete("stud", "roll_no = 1");

选择记录

要在数据库中选择记录,请使用get函数,如下表所示 -

Syntax

get([ $table = '' [, $limit = NULL [, $offset = NULL ]]])

Parameters

  • $tablestring ) - 查询数组的表

  • $limitint ) - LIMIT子句

  • $offsetint ) - OFFSET子句

Returns

CI_DB_result instance (method chaining)

Return Type

CI_DB_result

使用以下代码从数据库中获取所有记录。 第一个语句从“stud”表中获取所有记录并返回该对象,该对象将存储在$ query对象中。 第二个语句使用$ query对象调用result()函数将所有记录作为数组获取。

$query = $this->db->get("stud"); 
$data['records'] = $query->result();

关闭连接

可以通过执行以下代码手动关闭数据库连接 -

$this->db->close(); 

例子 (Example)

创建一个名为Stud_controller.php的控制器类,并将其保存在application/controller/Stud_controller.php

这是一个完整的例子,其中执行所有上述操作。 在执行以下示例之前,请按照本章开头的说明创建数据库和表,并对存储在application/config/database.php中的数据库配置文件进行必要的更改。

<?php 
   class Stud_controller extends CI_Controller {
      function __construct() { 
         parent::__construct(); 
         $this->load->helper('url'); 
         $this->load->database(); 
      } 
      public function index() { 
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->helper('url'); 
         $this->load->view('Stud_view',$data); 
      } 
      public function add_student_view() { 
         $this->load->helper('form'); 
         $this->load->view('Stud_add'); 
      } 
      public function add_student() { 
         $this->load->model('Stud_Model');
         $data = array( 
            'roll_no' => $this->input->post('roll_no'), 
            'name' => $this->input->post('name') 
         ); 
         $this->Stud_Model->insert($data); 
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
      public function update_student_view() { 
         $this->load->helper('form'); 
         $roll_no = $this->uri->segment('3'); 
         $query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
         $data['records'] = $query->result(); 
         $data['old_roll_no'] = $roll_no; 
         $this->load->view('Stud_edit',$data); 
      } 
      public function update_student(){ 
         $this->load->model('Stud_Model');
         $data = array( 
            'roll_no' => $this->input->post('roll_no'), 
            'name' => $this->input->post('name') 
         ); 
         $old_roll_no = $this->input->post('old_roll_no'); 
         $this->Stud_Model->update($data,$old_roll_no); 
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
      public function delete_student() { 
         $this->load->model('Stud_Model'); 
         $roll_no = $this->uri->segment('3'); 
         $this->Stud_Model->delete($roll_no); 
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
   } 
?>

创建一个名为Stud_Model.php的模型类,并将其保存在application/models/Stud_Model.php

<?php 
   class Stud_Model extends CI_Model {
      function __construct() { 
         parent::__construct(); 
      } 
      public function insert($data) { 
         if ($this->db->insert("stud", $data)) { 
            return true; 
         } 
      } 
      public function delete($roll_no) { 
         if ($this->db->delete("stud", "roll_no = ".$roll_no)) { 
            return true; 
         } 
      } 
      public function update($data,$old_roll_no) { 
         $this->db->set($data); 
         $this->db->where("roll_no", $old_roll_no); 
         $this->db->update("stud", $data); 
      } 
   } 
?> 

创建一个名为Stud_add.php的视图文件,并将其保存在application/views/Stud_add.php

<!DOCTYPE html> 
<html lang = "en">
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head> 
   <body> 
         <?php 
            echo form_open('Stud_controller/add_student');
            echo form_label('Roll No.'); 
            echo form_input(array('id'=>'roll_no','name'=>'roll_no')); 
            echo "<br/>"; 
            echo form_label('Name'); 
            echo form_input(array('id'=>'name','name'=>'name')); 
            echo "<br/>"; 
            echo form_submit(array('id'=>'submit','value'=>'Add')); 
            echo form_close(); 
         ?> 
   </body>
</html>

创建一个名为Stud_edit.php的视图文件,并将其保存在application/views/Stud_edit.php

<!DOCTYPE html> 
<html lang = "en">
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head> 
   <body> 
      <form method = "" action = "">
         <?php 
            echo form_open('Stud_controller/update_student'); 
            echo form_hidden('old_roll_no',$old_roll_no); 
            echo form_label('Roll No.'); 
            echo form_input(array('id'⇒'roll_no',
               'name'⇒'roll_no','value'⇒$records[0]→roll_no)); 
            echo "
            "; 
            echo form_label('Name'); 
            echo form_input(array('id'⇒'name','name'⇒'name',
               'value'⇒$records[0]→name)); 
            echo "
            "; 
            echo form_submit(array('id'⇒'sub mit','value'⇒'Edit')); 
            echo form_close();
         ?> 
      </form> 
   </body>
</html>

创建一个名为Stud_view.php的视图文件,并将其保存在application/views/Stud_view.php

<!DOCTYPE html> 
<html lang = "en">
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head>
   <body> 
      <a href = "<?php echo base_url(); ?>
         index.php/stud/add_view">Add</a>
      <table border = "1"> 
         <?php 
            $i = 1; 
            echo "<tr>"; 
            echo "<td>Sr#</td>"; 
            echo "<td>Roll No.</td>"; 
            echo "<td>Name</td>"; 
            echo "<td>Edit</td>"; 
            echo "<td>Delete</td>"; 
            echo "<tr>"; 
            foreach($records as $r) { 
               echo "<tr>"; 
               echo "<td>".$i++."</td>"; 
               echo "<td>".$r->roll_no."</td>"; 
               echo "<td>".$r->name."</td>"; 
               echo "<td><a href = '".base_url()."index.php/stud/edit/"
                  .$r->roll_no."'>Edit</a></td>"; 
               echo "<td><a href = '".base_url()."index.php/stud/delete/"
                  .$r->roll_no."'>Delete</a></td>"; 
               echo "<tr>"; 
            } 
         ?>
      </table> 
   </body>
</html>

application/config/routes.php的路由文件中进行以下更改,并在文件末尾添加以下行。

$route['stud'] = "Stud_controller"; 
$route['stud/add'] = 'Stud_controller/add_student'; 
$route['stud/add_view'] = 'Stud_controller/add_student_view'; 
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1'; 
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';

现在,让我们通过在浏览器中访问以下URL来执行此示例。 用您的URL替换yoursite.com。

http://yoursite.com/index.php/stud
↑回到顶部↑
WIKI教程 @2018