為了方便框架的使用,我們?cè)诎惭b好之后,可以連接數(shù)據(jù)庫,這樣數(shù)據(jù)的導(dǎo)入和應(yīng)用也將變得更加方便。本篇為大家?guī)淼氖莐ohana框架連接數(shù)據(jù)庫的方法,鑒于大家對(duì)于這種框架不是很熟悉,所以整理了詳細(xì)的連接方法,在配置后還可以用kohana進(jìn)行數(shù)據(jù)查詢,下面一起來看看如何連接吧。
1、添加database支持。在kohana\application\bootstrap.php下找到如下段
Kohana::modules(array( // 'auth' => MODPATH.'auth', // Basic authentication // 'cache' => MODPATH.'cache', // Caching with multiple backends // 'codebench' => MODPATH.'codebench', // Benchmarking tool // 'database' => MODPATH.'database', // Database access // 'image' => MODPATH.'image', // Image manipulation // 'orm' => MODPATH.'orm', // Object Relationship Mapping // 'unittest' => MODPATH.'unittest', // Unit testing // 'userguide' => MODPATH.'userguide', // User guide and API documentation ));
去掉database前面的注釋。
2、在kohana\application\config下添加database.conf配置文件,內(nèi)容如下
<?php defined('SYSPATH') or die('No direct access allowed.');
return array
(
'default' => array
(
'type' => 'mysql',
'connection' => array(
'hostname' => 'localhost',
'username' => 'root',
'password' => 'password',
'persistent' => FALSE,
'database' => 'kohanademo',
),
'table_prefix' => '',
'charset' => 'utf8',
'profiling' => TRUE,
),
);
?>修改對(duì)應(yīng)的數(shù)據(jù)庫名和密碼就好。
3、在代碼中添加數(shù)據(jù)庫查詢段,kohana\application\classes\controller\user\user.php內(nèi)容修改如下
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User_User extends Controller {
public function action_index()
{
$username = Session::instance()->get('username');
$this->response->body('logined:'.$username);
}
public function action_login()
{
if($this->request->post())
{
$username = $this->request->post('username');
$password = $this->request->post('password');
$query = DB::query(Database::SELECT, "SELECT username FROM user WHERE username=:username AND password=:password");
$query->param(':username', $username);
$query->param(':password', $password);
$user = $query->execute()->current();
if(count($user) > 0)
{
Session::instance()->set('username',$username);
}
$this->request->redirect('/user/user/index');
}
}
}
?>以上就是php中kohana框架連接數(shù)據(jù)庫的方法,在完成了這部分的配置后,我們可以調(diào)用一些數(shù)據(jù)進(jìn)行查詢,大家也參照上面的步驟來進(jìn)行嘗試吧。
