How to configure a database connection in Yii?

Member

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

How to configure a database connection in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 2 years ago

@deron 

Yii is a PHP framework that provides various components for developing web applications. One of the important components in Yii is the database connection, which is used to connect to a database and execute SQL queries. Here are the steps to configure a database connection in Yii:

  1. Open the main configuration file config/web.php or config/console.php depending on whether you are configuring the connection for a web application or a console application.
  2. In the components section of the configuration file, add a new configuration for the database connection, using the yiidbConnection class. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
'components' => [
    'db' => [
        'class' => 'yiidbConnection',
        'dsn' => 'mysql:host=localhost;dbname=mydatabase',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
    // other components
],


The dsn parameter specifies the Data Source Name for the database connection. In this example, we are connecting to a MySQL database running on the local machine, with a database name of mydatabase. The username and password parameters are used to authenticate with the database server.

  1. You can also configure other database options such as tablePrefix, schemaMap, enableSchemaCache, etc. based on your requirements.
  2. Save the configuration file and test the database connection by executing a SQL query using the Yii database connection object. For example:
1
2
3
$connection = Yii::$app->db;
$command = $connection->createCommand('SELECT * FROM mytable');
$rows = $command->queryAll();


This code retrieves all the rows from a table called mytable and stores them in the $rows variable.


By following these steps, you should be able to configure and use a database connection in Yii.