Home Backend Development PHP Tutorial Analyze the addition, deletion, query and modification of yii database_PHP tutorial

Analyze the addition, deletion, query and modification of yii database_PHP tutorial

Jul 21, 2016 pm 03:04 PM
yii code example copy storage access database method of parse

1. Database access method
Storage the first type
Used when saving tables
Example:

Copy code The code is as follows:

$post=new Post;
$post->title='samplepost';
$post-> ;content='content for thesample post';
$post->createTime=time();/$post->createTime=newCDbexpression_r('NOW()');
$post->save ();
$user_field_data= new user_field_data;
$user_field_data->flag=0;
$user_field_data->user_id=$profile->id;
$user_field_data->field_id =$_POST['emailhiden'];
$user_field_data->value1=$_POST['email'];
$user_field_data->save();

Note that when a table is stored 4 times, 4 handle news need to be created 4 times

Store the second type
After storing, we need to find the serial ID of this record. Do this $profile = new profile;$profile->id;

Store the third
for a safer way to bind variable types so that two records can be stored in the same table

Copy code The code is as follows:

$sql="insert intouser_field_data(user_id,field_id,flag,value1)values(:user_id,:field_id,:flag,:value1) ;";
$command=user_field_data::model()->dbConnection->createCommand($sql);
$command->bindParam(":user_id",$profile->id, PDO::PARAM_INT);
$command->bindParam(":field_id",$_POST['firstnamehiden'],PDO::PARAM_INT);
$command->bindParam(":flag", $tmpflag,PDO::PARAM_INT);
$command->bindParam(":value1",$_POST['firstname'],PDO::PARAM_STR);
$command->execute();
$command->bindParam(":user_id",$profile->id,PDO::PARAM_INT);
$command->bindParam(":field_id",$_POST['emailhiden'] ,PDO::PARAM_INT);
$command->bindParam(":flag",$tmpflag,PDO::PARAM_INT);
$command->bindParam(":value1",$_POST[' email'],PDO::PARAM_STR);
$rowchange =$command->execute();
if( $rowchange != 0){ Modification successful}//Used to judge
Note: This method can be used for update and delete
$sql="delete from profile whereid=:id";
$command=profile::model()->dbConnection->createCommand( $sql);
$command->bindParam(":id",$userid,PDO::PARAM_INT);
$this->rowflag=$command->execute();
$sql="update profile setpass=:pass,role=:role where id=:id";
$command=profile::model()->dbConnection->createCommand($sql);
$command->bindParam(":pass",$password,PDO::PARAM_STR);
$command->bindParam(":role",$role,PDO::PARAM_INT);
$command ->bindParam(":id",$userid,PDO::PARAM_INT);
$this->rowflag=$command->execute();
// Change the updateAll() mode in the same way
$sql="update user_field_data set flag =:flag where user_id= :user_id and field_id= :field_id ";
Original sql statement
$criteria = newCDbCriteria;
$criteria->condition = 'user_id = :user_id and field_id= :field_id';
$criteria->params =array(':user_id' => $userid,':field_id'=> $fieldid);
$arrupdate = array('flag'=> $flag);
if(user_field_data::model()->updateAll($arrupdate,$criteria)!= 0)
{
After the update is successful. . .
}

The fourth update and storage application use the same handle process:
First query whether the record exists, update it if it exists, and create it if it does not exist.
Note: 1. The variable queried for the first time must be consistent with the variable before save(). 2. When storing, you need to new the library object
Copy code The code is as follows:

$user_field_data =user_field_data: :model()->findByAttributes(
$attributes = array('user_id'=>Yii::app()->user->user_id, 'field_id'=> $key));
if($user_field_data !== null)
{
$user_field_data->value1= $value;
$user_field_data->save();
}
else
{
$user_field_data= new user_field_data;
$user_field_data->user_id= Yii::app()->user->user_id;
$user_field_data->field_id= $key;
$user_field_data->value1= $value;
$user_field_data->save();
}

Query
Note: When the project is not found, the entire object will be empty and needs to be determined like this
Copy the code The code is as follows:

if($rows !== null) When the object is not empty
{
returntrue;
}else{
returnfalse;
}
SELECT

Use
when reading tables. Example:
The first find()
Copy codeThe code is as follows:

// find the first row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with postID=10
$post=Post::model()->find('postID=:postID',array(':postID'=>10));
Same statement, expressed in another way
$criteria=new CDbCriteria;
$criteria->select='title';// only select the 'title' column
$criteria->condition= 'postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria); // $params is not needed

Second find()
Copy code The code is as follows :

$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID =:postID',
'params'=>array(':postID'=>10),
));
// find the row with the specified primarykey
$post= Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attributevalues
$post=Post::model()->findByAttributes( $attributes,$condition,$params);

Example:
The first findByAttributes()
$checkuser= user_field_data::model()-> ;findByAttributes(
array('user_id' =>Yii::app()->user->user_id, 'field_id'=> $fieldid));
The second type of findByAttributes ()
$checkuser =user_field_data::model()->findByAttributes(
$attributes = array('user_id'=>Yii::app()->user->user_id , 'field_id'=> $fieldid));
The third method is that when there are no conditions, params are not needed
$user_field_data=user_field_data::model()->findAllByAttributes(
$attributes = array('user_id'=> ':user_id'),
$condition = "field_id in(:fields)",
$params = array(':user_id'=>Yii: :app()->user->user_id, ':fields'=> "$rule->dep_fields"));
// find the first row using the specified SQLstatement
$post= Post::model()->findBySql($sql,$params);
Example
user_field_data::model()->findBySql("selectid from user_field_data where user_id = :user_id and field_id =:field_id ", array(':user_id' =>$userid,':field_id'=>$fieldid));
What is returned at this time is an object
The fourth method is to add other conditions
http://www.yiiframework.com/doc/api/CDbCriteria#limit-detail
$criteria = newCDbCriteria;
$criteria->select='newtime';//Select only Which fields to display must have the same names as those in the library, but you cannot write COUNT(newtime) as name like this
$criteria->join = 'LEFT JOINPost ON Post.id=Date.id'; //1. First. To add a relationship statement with the Post table in the relationship function 2.Date::model()->with('post')->findAll($criteria)
$criteria->group ='newtime' ;
$criteria->limit = 2; //They all start from 0, select a few
$criteria->offset = 2;//Which offset to start from
print_r(Date ::model()->findAll($criteria));
Get the number of rows or other numbers count
// get the number of rows satisfying the specified condition
$n=Post::model() ->count($condition,$params);
// get the number of rows using the specifiedSQL statement
$n=Post::model()->countBySql($sql,$params);
// check if there is at least a row satisfying the specified condition
$exists=Post::model()->exists($condition,$params);
UPDATE
Example:
Copy code The code is as follows:

$post=Post::model()->findByPk (10);
$post->title='new posttitle';
$post->save(); // save thechange to database
// update the rows matching the specifiedcondition
Post::model()->updateAll($attributes,$condition,$params);

Example: Or refer to the above example
Copy Code The code is as follows:

$c=new CDbCriteria;
$c->condition='something=1';
$c->limit =10;
$a=array('name'=>'NewName');
Post::model()->updateAll($a,$c);
// update the rows matching the specifiedcondition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);

例子
复制代码 代码如下:

$profile =profile::model()->updateByPk(
Yii::app()->user->user_id,
$attributes = array('pass' =>md5($_POST['password']), 'role' => 1));
// update counter columns in the rowssatisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);

DELETE
例子:
复制代码 代码如下:

$post=Post::model()->findByPk(10);// assuming there is a post whose ID is 10
$post->delete(); // delete therow from the database table
// delete the rows matching the specifiedcondition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specifiedcondition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);
COMPARE

目前可以取出的
1.//$allquestion=field::model()->findAllBySql("selectlabel from field where step_id = :time1 ", array(':time1'=>1));
2. //$criteria=new CDbCriteria;
//$criteria->select='label,options';
//$criteria->condition='step_id=:postID';
//$criteria->params=array(':postID'=>1);
//$allquestion=field::model()->findAll($criteria);
//$allquestion=field::model()->find("",array("label"));
可以与在models文件夹中的 库连接文件relations()函数合用,这样可以联合查询
$criteria=newCDbCriteria;
$criteria->condition='field.step_id=1';
$this->_post=field::model()->with('step')->findAll($criteria);
这样出来的数组里面包含step表中的值,且这个值的条件为step.id=field.step_id
public functionrelations()
{
return array(
'step'=>array(self::BELONGS_TO,'step', 'step_id'),
);
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327748.htmlTechArticle1. 存取数据库方法 存储第一种 存表时候用到 例子: 复制代码 代码如下: $post=new Post; $post-title='samplepost'; $post-content='content for thesample post...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

See all articles