How to retrieve data from the database in Yii?

Member

by lily , in category: PHP Frameworks , a year ago

How to retrieve data from the database in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 9 months ago

@lily 

To retrieve data from a database in Yii, you can follow these steps:

  1. Define a model class that represents the table you want to retrieve data from. For example, if you have a table named users, you can create a model class named User and extend it from CActiveRecord.
1
2
3
4
5
class User extends CActiveRecord
{
    // define attributes and database table name
    // ...
}


  1. Use the find method of the model class to retrieve data from the database. For example, you can retrieve all users by calling the findAll method.
1
$users = User::model()->findAll();


This will return an array of User objects.

  1. You can also use criteria to retrieve specific data from the database. For example, you can retrieve all users whose age is greater than 25.
1
2
3
4
$criteria = new CDbCriteria;
$criteria->condition = 'age > :age';
$criteria->params = array(':age' => 25);
$users = User::model()->findAll($criteria);


This will return an array of User objects whose age is greater than 25.

  1. You can use other methods of the model class to retrieve data. For example, you can retrieve a single user by calling the findByPk method.
1
$user = User::model()->findByPk($id);


This will return a single User object with the primary key $id.