3 ways to operate a database in Yii _php tips

Source: Internet
Author: User
First, the implementation of native too SQL PDO way.
Copy Code code as follows:
$sql = ""//original Ecological SQL statement
Xx::model ()->dbconnection->createcommand ($sql)->execute ();

Second, Active record mode
(1) New Way
Copy Code code as follows:
$post =new Post;
$post->title= ' sample post ';
$post->content= ' post body content ';
$post->save ();

(2) Criteria method
You can also use $condition to specify more complex query conditions. Without the use of strings, we can make $condition an instance of Cdbcriteria, which allows us to specify conditions that are not limited to WHERE.
Copy Code code as follows:
$criteria =new Cdbcriteria;
$criteria->select= ' title '; Select only ' title ' column
$criteria->condition= ' postid=:p ostid ';
$criteria->params=array (':p ostid ' =>10);
$post =post::model ()->find ($criteria);

One way to replace Cdbcriteria is to pass an array to the Find method. The keys and values of the array correspond to the attribute names and values of the standard (criterion), and the example above can be rewritten as follows:
Copy Code code as follows:
$post =post::model ()->find Array (
' Select ' => ' title ',
' Condition ' => ' postid=:p ostid ',
' Params ' =>array (':p ostid ' =>10),
));

When a query condition is about matching several columns by a specified value, we can use Findbyattributes (). We make the $attributes argument an array of values indexed by the column name. In some frameworks, this task can be implemented by invoking a method similar to Findbynameandtitle. While this approach may seem tempting, it often causes confusion, conflict, and case sensitivity for column names.
Three, Query Builder way
Copy Code code as follows:
$user = Yii::app ()->db->createcommand ()
->select (' ID, username, profile ')
->from (' Tbl_user u ')
->join (' Tbl_profile p ', ' u.id=p.user_id ')
->where (' Id=:id ', Array (': Id ' => $id))
->queryrow ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.