


Analyze the addition, deletion, query and modification of yii database_PHP tutorial
1. Database access method
Storage the first type
Used when saving tables
Example:
$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
$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
$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
if($rows !== null) When the object is not empty
{
returntrue;
}else{
returnfalse;
}
SELECT
Use
when reading tables. Example:
The first find()
// 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()
$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:
$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
$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'),
);
}

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment