1. 程式人生 > >【PHP】codeigniter框架中的表單輔助函式

【PHP】codeigniter框架中的表單輔助函式

這裡以登入介面為例,演示codeigniter框架的表單輔助函式。

首先需要解決的一個問題是,如何將view中使用者填寫的資料提交給控制器。我在這裡使用了表單輔助函式

$this->load->helper('form');

新建控制器,鍵入程式碼

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {


  public function __construct()
	{
    	parent::__construct();
    	//引入表單輔助函式
    	$this->load->helper('form');
	}

	public function index()
	{	//載入view	
		$this->load->view('login');
	}
	
	//獲取表單資料進行處理
	public function UserLogin() {
		echo $_POST ['username'];
	}
	
}
隨後新建一個檢視,鍵入程式碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登入</title>
</head>
<?php echo form_open('login/UserLogin'); ?>
<div>
	<table>
		<tr>
			<td>使用者名稱</td>
			<td><input type="text" name="username"></td>
		</tr>
		<tr>
			<td>密碼</td>
			<td><input type="password" name="password"></td>
		</tr>
		<tr>
			<td>
			<input type="submit" value="登入">
			</td>
		</tr>
	</table>
</div>
</form>
</html>


程式碼中form標籤只有結束沒有開始。

其實不難想到,開始標籤與第二行的php程式碼有關。

form_open函式會生成一個 form 起始標籤,關於它的更多詳情可以參考CI的使用者手冊,表單輔助函式那部分。

到這裡為止,view已經順利地把表單中的資料傳輸給了controller。效果如下↓