当前位置:网站首页>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
边栏推荐
- LeetCode:1189. The maximum number of "balloons" -- simple
- [Yu Yue education] higher mathematics of Nanchang University (2) reference materials
- Efficiency tool +wps check box shows the solution to the sun problem
- [Digital IC manual tearing code] Verilog automatic beverage machine | topic | principle | design | simulation
- Earned value management EVM detailed explanation and application, example explanation
- Technology sharing | packet capturing analysis TCP protocol
- JS learning notes OO create suspicious objects
- jvm:大对象在老年代的分配
- Numpy download and installation
- C language char, wchar_ t, char16_ t, char32_ Relationship between T and character set
猜你喜欢
Happy sound 2[sing.2]
ViT论文详解
C# 如何在dataGridView里设置两个列comboboxcolumn绑定级联事件的一个二级联动效果
[Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)
1292_ Implementation analysis of vtask resume() and xtask resume fromisr() in freeros
小满网络模型&http1-http2 &浏览器缓存
Tiktok will push the independent grass planting app "praiseworthy". Can't bytes forget the little red book?
一行代码可以做些什么?
The golden age of the U.S. technology industry has ended, and there have been constant lamentations about chip sales and 30000 layoffs
【sciter】: 基于 sciter 封装通知栏组件
随机推荐
Z function (extended KMP)
抖音將推獨立種草App“可頌”,字節忘不掉小紅書?
小满网络模型&http1-http2 &浏览器缓存
What is the difference between animators and animators- What is the difference between an Animator and an Animation?
[Li Kou brush questions] 32 Longest valid bracket
GPS from getting started to giving up (XIII), receiver autonomous integrity monitoring (RAIM)
What is the RDD operator in spark
用aardio写一个旋转验证码标注小工具
Solution to the problem of UOS boot prompt unlocking login password ring
Redistemplate common collection instructions opsforhash (IV)
MySQL related terms
GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
红杉中国,刚刚募资90亿美元
NPM run dev start project error document is not defined
Five wars of Chinese Baijiu
搜素专题(DFS )
Kohana 数据库
Broadcast variables and accumulators in spark
Oracle性能分析3:TKPROF简介
[Chongqing Guangdong education] Information Literacy of Sichuan Normal University: a new engine for efficiency improvement and lifelong learning reference materials