当前位置:网站首页>Kohana database

Kohana database

2022-07-06 21:57:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack .

As long as you don't use the tutorial on the official website , I found out by myself , There is a mistake , When we point it out , Oh ,, Well, progress together ~

First configuration :modules\database\config\database.php

<?php
'default' => array(
		'type'       => 'pdo',
		'connection' => array(
			/**
			 * The following options are available for PDO:
			 *
			 * string   dsn         Data Source Name
			 * string   username    database username
			 * string   password    database password
			 * boolean  persistent  use persistent connections?
			 */
			'dsn'        => 'mysql:host=localhost;dbname=kohana',
			'username'   => '******',//
			'password'   => '******',//
			'persistent' => FALSE,
		),
		/**
		 * The following extra options are available for PDO:
		 *
		 * string   identifier  set the escaping identifier
		 */
		'table_prefix' => 'ko_',
		'charset'      => 'utf8',
		'caching'      => FALSE,
		'profiling'    => TRUE,
),
 Be able to configure multiple database configurations ~

After configuration, you can use

You can use it after configuration

You can do this in your controller

data Library instance

There are two database instances

1.DB Database instance

2. database Database instance

among DB It's right database The second encapsulation of

The following description describes the use of two database examples

Database

How to get it :

<?php
$database=Database::instance();// To be able to achieve database example 
# The exception is in the model ,dababase As the only passing parameter of the model constructor , And in the model $this->_db attribute 
$database=$this->_db;
 usage :( If in the model )
 insert data :
<?php
$sql="INSERT INTO `kohana`.`user` (`name` ,`age` )VALUES ( 'test', '1'), ( 'test2', '2')";
$dat=$this->_db->query(Database::INSERT,$sql,false);
# return  Of the two values returned , The first one is self-motivated ID, If it's not true , The second is the number of rows affected  

Update data :

<?php
$sql="UPDATE `ko_users` SET `user_name` = 'test111q1'  ";
$dat=$this->_db->query(Database::UPDATE,$sql,false);
#return  Returns the number of affected rows 
 Delete data :
<?php
$sql="DELETE FROM `kohana`.`user` WHERE `user`.`id` = 1";
$dat=$this->_db->query(Database::DELETE,$sql,false);
#return  Returns the number of affected rows 
 Query data :
<?php $sql="select * from ko_com_var"; $res=$this->_db->query(Database::SELECT,$sql,false); # Get all the query data  $res->as_array(); # Get a query result  $res->offsetGet(0); # Get the specified field value of a specific record  $res->get("name"); # Move the pointer and get the specified field  $res->next()->get("name"); $res->prev()->get("name"); # Calculate the total number of results  $res->count(); # There are other methods not listed one by one , Please check the manual 

Others often use help functions :

<?php
# Filter strings with , I don't know why I put it in this single example , It should be public ~, Maybe there are differences in the filtering of each database 
$str=$this->_db->escape("ddddd  ddd");
# Table prefix , This is often used ~
$str=$this->_db->table_prefix();
# There are other view help , No introduction 

DB Case use ( Here's a demonstration in Kohana The environment can )

There are two ways :

The first one is :

Below execute(); There is a database adapter parameter , When there are multiple data connections, specify the database to operate , The one in the configuration file KEY value

insert data :

<?php $sql="INSERT INTO `kohana`.`user` (`name` ,`age` )VALUES ( 'test', '1'), ( 'test2', '2')"; # In fact, it can also be used Database::UPDATE, The result only returns the number of affected rows , It's just better to follow the specifications . ha-ha ~, Above Database Can also  $dat=DB::query(Database::INSERT,$sql); $row=$dat->execute(); # Of the two values returned , The first one is self-motivated ID, If it's not true , The second is the number of rows affected  Kohana::debug($row);

Data update :

<?php
$sql="UPDATE `user` SET `name` = 'test2' WHERE `user`.`id` =1 ";
$dat=DB::query(Database::UPDATE,$sql);
$row=$dat->execute();
# Returns the number of affected rows 
echo Kohana::debug($row);
 Data deletion :
<?php $sql="DELETE FROM `kohana`.`user` WHERE `user`.`id` = 1"; $dat=DB::query(Database::DELETE,$sql); $row=$dat->execute(); # Returns the number of affected rows  echo Kohana::debug($row);

Data query :

<?php$sql="select * from user";$dat=DB::query(Database::SELECT,$sql);# Specify the database to fetch data $row=$dat->execute($database)->offsetGet(0);# The default database fetches data , And the above Database equally , All return to Database_Result_Cached object , Implemented iterator pattern $rus=$dat->execute();# Get some results $row=$rus->offsetGet(0);# Achieve full results $allrow=$rus->as_array();# Get the specified field value of a specific record $no1name=$rus->get("name");# Move the array pointer , And take the specified field value $no2name=$rus->next()->get("name");# Pointer to the current echo $rus->key();# Move the array pointer , And take the specified field value echo $no1name=$rus->prev()->get('name');# Take the number of lines echo $rus->count();

another :( The official website document is called query mode , It fails to work well , ha-ha , It's easy to use )

insert data :

<?php
$query = DB::insert('user', array('user', 'age'))
		->values(array('test1', '11'));
$query->execute();
# Return as above 

Update data :

<?php
$query = DB::update('user')
		->set(array('age' => '100'))
		->where('user', '=', 'test1');
$query->execute();
# Return as above 

Delete data :

<?php
$query = DB::delete('user')
		->where('age', 'IN', array('100', '11'));
$query->execute();
# Return as above 

Query data :

<?php
$query = DB::select()->from('user')->where("id","=","1");
$res=$query->execute();
# Same as above ,$res yes Database_Result_Cached object 
$res->as_array();
# Other methods are not demonstrated ~
 Note appended :
 Data binding , Copy an official example , Should be very easy, It's easier to understand 
<?php
$query = DB::query(Database::INSERT, 'INSERT INTO users (username, password) VALUES (:user, :pass)')      
->bind(':user', $username)    
->bind(':pass', $password);  
foreach ($new_users as $username => $password){    
	$query->execute();
}

Basically it , I don't use it very often , I don't want to describe , It mainly introduces the complete ,

Copyright notice : This article is the original article of the blogger , Blog , Do not reprint without permission .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117064.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061343425967.html