当前位置:网站首页>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
边栏推荐
- C language: comprehensive application of if, def and ifndef
- C语言:#if、#def和#ifndef综合应用
- jvm:大对象在老年代的分配
- SQL:存储过程和触发器~笔记
- 华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
- Basic introduction of figure
- 14 years Bachelor degree, transferred to software testing, salary 13.5k
- Shake Sound poussera l'application indépendante de plantation d'herbe "louable", les octets ne peuvent pas oublier le petit livre rouge?
- [Li Kou brushing questions] one dimensional dynamic planning record (53 change exchanges, 300 longest increasing subsequence, 53 largest subarray and)
- Depth first traversal (DFS) and breadth first traversal (BFS)
猜你喜欢

用aardio写一个旋转验证码标注小工具

Unity3D学习笔记6——GPU实例化(1)

Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic

bat脚本学习(一)

Bat script learning (I)

Tiktok will push the independent grass planting app "praiseworthy". Can't bytes forget the little red book?

GPS从入门到放弃(十七) 、对流层延时

GPS from getting started to giving up (XIII), receiver autonomous integrity monitoring (RAIM)

numpy 下载安装

GPS从入门到放弃(十三)、接收机自主完好性监测(RAIM)
随机推荐
guava:创建immutableXxx对象的3种方式
string的底层实现
【sciter Bug篇】多行隐藏
Reptile practice (V): climbing watercress top250
What can one line of code do?
Redistemplate common collection instructions opsforhash (IV)
Method return value considerations
AI 企业多云存储架构实践 | 深势科技分享
保存和检索字符串
11、 Service introduction and port
Shake Sound poussera l'application indépendante de plantation d'herbe "louable", les octets ne peuvent pas oublier le petit livre rouge?
The underlying implementation of string
ViT论文详解
麦趣尔砸了小众奶招牌
The underlying implementation of string
用aardio写一个旋转验证码标注小工具
npm run dev启动项目报错 document is not defined
Dialogue with Jia Yangqing, vice president of Alibaba: pursuing a big model is not a bad thing
The role of applicationmaster in spark on Yan's cluster mode
PostgreSQL modifies the password of the database user