要从数据库中获取所有数据, 将在CodeIgniter的Model文件夹中再创建一页。控制器和视图的文件也会有一些变化。
控制器文件(Baby_form.php)如下所示。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Baby_form extends CI_Controller {
public function __construct()
{
parent::__construct();
//calling model
$this->load->model("Babymodel", "a");
}
public function index()
{
$this->load->view("baby_form_select");
}
function savingdata()
{
//this array is used to get fetch data from the view page.
$data = array(
'name' => $this->input->post('name'), 'meaning' => $this->input->post('meaning'), 'gender' => $this->input->post('gender'), 'religion' => $this->input->post('religion')
);
//insert data into database table.
$this->db->insert('baby', $data);
redirect("baby_form/index");
}
}
?>
我们添加了一个构造函数来加载模型页面。添加突出显示的代码以获取插入的记录。现在我们的视图页面为baby_form_select.php
查看文件(baby_form_select.php)如下所示。
<!DOCTYPE html>
<html>
<head>
<title>Baby Form Add</title>
</head>
<body>
<form method="post" action="<?php echo site_url('baby_form/savingdata'); ?>">
<table>
<tr>
<td>Name:</td>
<td>:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Meaning:</td>
<td>:</td>
<td><input type="text" name="meaning"></td>
</tr>
<tr>
<td>Gender:</td>
<td>:</td>
<td><input type="text" name="gender"></td>
</tr>
<tr>
<td>Religion:</td>
<td>:</td>
<td><input type="text" name="religion"></td>
</tr><br><br>
<tr>
<input type="submit" name="submit" value="Save">
</tr>
</table>
</form>
<table border="1">
<thead>
<th>ID</th>
<th>NAME</th>
<th>MEANING</th>
<th>GENDER</th>
<th>RELIGION</th>
<th>ACTION</th>
</thead>
<tbody>
<?php
foreach($this->a->fetchtable() as $row)
{
//name has to be same as in the database.
echo "<tr>
<td>$row->id</td>
<td>$row->name</td>
<td>$row->meaning</td>
<td>$row->gender</td>
<td>$row->religion</td>
</tr>";
}
?>
</tbody>
</table>
</body>
</html>
baby_form_select.php文件中的代码与baby_form_add.php相同。添加以上代码以获取记录。
在这里, 我们借助foreach循环在表中获取了记录。创建函数fetchtable()来获取记录。
模型文件(babymodel.php)如下所示。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Babymodel extends CI_Model {
function __construct()
{
//call model constructor
parent::__construct();
}
function fetchtable()
{
$query = $this->db->get('baby');
return $query->result();
}
}
?>
在URL中, 输入http://localhost/CodeIgniter/index.php/Baby_form
查看上面的快照, 所有数据均已从“ baby”表中获取。
评论前必须登录!
注册