当前位置:网站首页>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
边栏推荐
- JS method to stop foreach
- Solution to the problem of UOS boot prompt unlocking login password ring
- mysql根据两个字段去重
- [asp.net core] set the format of Web API response data -- formatfilter feature
- Some problems about the use of char[] array assignment through scanf..
- [Li Kou brush questions] 32 Longest valid bracket
- Earned value management EVM detailed explanation and application, example explanation
- 【sciter】: 基于 sciter 封装通知栏组件
- OpenCV300 CMake生成project在项目过程中的问题
- Binary tree node at the longest distance
猜你喜欢

【MySQL】Online DDL详解

GPS从入门到放弃(十四)、电离层延时

抖音將推獨立種草App“可頌”,字節忘不掉小紅書?

华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖

Enhance network security of kubernetes with cilium

Efficiency tool +wps check box shows the solution to the sun problem

AI 企业多云存储架构实践 | 深势科技分享

Earned value management EVM detailed explanation and application, example explanation

MPLS experiment

一行代码可以做些什么?
随机推荐
Univariate cubic equation - relationship between root and coefficient
Hill | insert sort
Make menuconfig has a recipe for target 'menuconfig' failed error
MySQL removes duplicates according to two fields
华为在多个行业同时出击,吓人的技术让欧美企业瑟瑟发抖
GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
麦趣尔砸了小众奶招牌
string的底层实现
LeetCode学习记录(从新手村出发之杀不出新手村)----1
ROS error: could not find a package configuration file provided by "move_base“
50 commonly used numpy function explanations, parameters and usage examples
MPLS experiment
记一次清理挖矿病毒的过程
What is the difference between animators and animators- What is the difference between an Animator and an Animation?
Redistemplate common collection instructions opsforset (V)
Intelligent online customer service system source code Gofly development log - 2 Develop command line applications
Oracle性能分析3:TKPROF简介
Fzu 1686 dragon mystery repeated coverage
Technology sharing | packet capturing analysis TCP protocol
20 large visual screens that are highly praised by the boss, with source code templates!