当前位置:网站首页>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
边栏推荐
- Caching strategies overview
- GPS从入门到放弃(十七) 、对流层延时
- GPS从入门到放弃(十五)、DCB差分码偏差
- Quick access to video links at station B
- C how to set two columns comboboxcolumn in DataGridView to bind a secondary linkage effect of cascading events
- LeetCode:1189. The maximum number of "balloons" -- simple
- Sequoia China, just raised $9billion
- GPS du début à l'abandon (XIII), surveillance autonome de l'intégrité du récepteur (raim)
- Z function (extended KMP)
- Hill | insert sort
猜你喜欢
What can one line of code do?
Shake Sound poussera l'application indépendante de plantation d'herbe "louable", les octets ne peuvent pas oublier le petit livre rouge?
小满网络模型&http1-http2 &浏览器缓存
功能强大的国产Api管理工具
Checkpoint of RDD in spark
50 commonly used numpy function explanations, parameters and usage examples
C how to set two columns comboboxcolumn in DataGridView to bind a secondary linkage effect of cascading events
Method return value considerations
【MySQL】Online DDL详解
[Chongqing Guangdong education] Information Literacy of Sichuan Normal University: a new engine for efficiency improvement and lifelong learning reference materials
随机推荐
Sql: stored procedures and triggers - Notes
GPS从入门到放弃(十六)、卫星时钟误差和卫星星历误差
numpy 下载安装
guava: Multiset的使用
What can one line of code do?
C语言:#if、#def和#ifndef综合应用
功能强大的国产Api管理工具
[go][reprint]vscode run a HelloWorld example after configuring go
The golden age of the U.S. technology industry has ended, and there have been constant lamentations about chip sales and 30000 layoffs
uni-app App端半屏连续扫码
JPEG2000-Matlab源码实现
GPS从入门到放弃(十四)、电离层延时
GPS从入门到放弃(十七) 、对流层延时
14 years Bachelor degree, transferred to software testing, salary 13.5k
Intelligent online customer service system source code Gofly development log - 2 Develop command line applications
Basic introduction of figure
用aardio写一个旋转验证码标注小工具
Sparkshuffle process and Mr shuffle process
C language: comprehensive application of if, def and ifndef
Vit paper details