How to retrieve data from the database in Yii?

Member

by lily , in category: PHP Frameworks , 2 years ago

How to retrieve data from the database in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 2 years 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.

Related Threads:

How to save data to the database in Yii?
How to securely store and retrieve sensitive data in PHP?
How to configure a database connection in Yii?
How to delete data from database in laravel?
How to request data from database in laravel?
How to get data from database in Symfony?