Database Configuration CodeIgniter

Database Configuration CodeIgniter

Database Configuration

CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at application/config/database.php. You can also set database connection values for specific environments by placing database.php in the respective environment config folder.

The config settings are stored in a multi-dimensional array with this prototype:

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'database_name',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => TRUE,
        'db_debug' => TRUE,
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array()
);

Some database drivers (such as PDO, PostgreSQL, Oracle, ODBC) might require a full DSN string to be provided. If that is the case, you should use the ‘dsn’ configuration setting, as if you’re using the driver’s underlying native PHP extension, like this:

// PDO
$db['default']['dsn'] = 'pgsql:host=localhost;port=5432;dbname=database_name';

// Oracle
$db['default']['dsn'] = '//localhost/XE';

Note

If you do not specify a DSN string for a driver that requires it, CodeIgniter will try to build it with the rest of the provided settings.

Note

If you provide a DSN string and it is missing some valid settings (e.g. the database character set), which are present in the rest of the configuration fields, CodeIgniter will append them.

You can also specify failovers for the situation when the main connection cannot connect for some reason. These failovers can be specified by setting the failover for a connection like this:

$db['default']['failover'] = array(
                array(
                        'hostname' => 'localhost1',
                        'username' => '',
                        'password' => '',
                        'database' => '',
                        'dbdriver' => 'mysqli',
                        'dbprefix' => '',
                        'pconnect' => TRUE,
                        'db_debug' => TRUE,
                        'cache_on' => FALSE,
                        'cachedir' => '',
                        'char_set' => 'utf8',
                        'dbcollat' => 'utf8_general_ci',
                        'swap_pre' => '',
                        'encrypt' => FALSE,
                        'compress' => FALSE,
                        'stricton' => FALSE
                ),
                array(
                        'hostname' => 'localhost2',
                        'username' => '',
                        'password' => '',
                        'database' => '',
                        'dbdriver' => 'mysqli',
                        'dbprefix' => '',
                        'pconnect' => TRUE,
                        'db_debug' => TRUE,
                        'cache_on' => FALSE,
                        'cachedir' => '',
                        'char_set' => 'utf8',
                        'dbcollat' => 'utf8_general_ci',
                        'swap_pre' => '',
                        'encrypt' => FALSE,
                        'compress' => FALSE,
                        'stricton' => FALSE
                )
        );

You can specify as many failovers as you like.

The reason we use a multi-dimensional array rather than a more simple one is to permit you to optionally store multiple sets of connection values. If, for example, you run multiple environments (development, production, test, etc.) under a single installation, you can set up a connection group for each, then switch between groups as needed. For example, to set up a “test” environment you would do this:

$db['test'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'database_name',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => TRUE,
        'db_debug' => TRUE,
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'compress' => FALSE,
        'encrypt' => FALSE,
        'stricton' => FALSE,
        'failover' => array()
);

Then, to globally tell the system to use that group you would set this variable located in the config file:

$active_group = 'test';

Note

The name ‘test’ is arbitrary. It can be anything you want. By default we’ve used the word “default” for the primary connection, but it too can be renamed to something more relevant to your project.

Query Builder

The Query Builder Class is globally enabled or disabled by setting the $query_builder variable in the database configuration file to TRUE/FALSE (boolean). The default setting is TRUE. If you are not using the query builder class, setting it to FALSE will utilize fewer resources when the database classes are initialized.

$query_builder = TRUE;

Note

that some CodeIgniter classes such as Sessions require Query Builder to be enabled to access certain functionality.

Explanation of Values:

Name ConfigDescription
dsnThe DSN connect string (an all-in-one configuration sequence).
hostnameThe hostname of your database server. Often this is ‘localhost’.
usernameThe username used to connect to the database.
passwordThe password used to connect to the database.
databaseThe name of the database you want to connect to.
dbdriverThe database type. ie: mysqli, postgre, odbc, etc. Must be specified in lower case.
dbprefixAn optional table prefix which will added to the table name when running Query Builder queries. This permits multiple CodeIgniter installations to share one database.
pconnectTRUE/FALSE (boolean) – Whether to use a persistent connection.
db_debugTRUE/FALSE (boolean) – Whether database errors should be displayed.
cache_onTRUE/FALSE (boolean) – Whether database query caching is enabled, see also Database Caching Class.
cachedirThe absolute server path to your database query cache directory.
char_setThe character set used in communicating with the database.
dbcollatThe character collation used in communicating with the database NoteOnly used in the ‘mysql’ and ‘mysqli’ drivers.
swap_preA default table prefix that should be swapped with dbprefix. This is useful for distributed applications where you might run manually written queries, and need the prefix to still be customizable by the end user.
schemaThe database schema, defaults to ‘public’. Used by PostgreSQL and ODBC drivers.
encryptWhether or not to use an encrypted connection. ‘mysql’ (deprecated), ‘sqlsrv’ and ‘pdo/sqlsrv’ drivers accept TRUE/FALSE ‘mysqli’ and ‘pdo/mysql’ drivers accept an array with the following options: ‘ssl_key’ – Path to the private key file ‘ssl_cert’ – Path to the public key certificate file ‘ssl_ca’ – Path to the certificate authority file ‘ssl_capath’ – Path to a directory containing trusted CA certificates in PEM format ‘ssl_cipher’ – List of allowed ciphers to be used for the encryption, separated by colons (‘:’) ‘ssl_verify’ – TRUE/FALSE; Whether to verify the server certificate or not (‘mysqli’ only)
compressWhether or not to use client compression (MySQL only).
strictonTRUE/FALSE (boolean) – Whether to force “Strict Mode” connections, good for ensuring strict SQL while developing an application.
portThe database port number. To use this value you have to add a line to the database config array. $db[‘default’][‘port’] = 5432;

Note

Depending on what database platform you are using (MySQL, PostgreSQL, etc.) not all values will be needed. For example, when using SQLite you will not need to supply a username or password, and the database name will be the path to your database file. The information above assumes you are using MySQL.

Database Quick Start: Example Code CodeIgniter

Database Quick Start: Example Code CodeIgniter

Database Quick Start: Example Code

The following page contains example code showing how the database class is used. For complete details please read the individual pages describing each function.

Initializing the Database Class

The following code loads and initializes the database class based on your configuration settings:

$this->load->database();

Once loaded the class is ready to be used as described below.

Note: If all your pages require database access you can connect automatically. See the connecting page for details.

Standard Query With Multiple Results (Object Version)

$query = $this->db->query('SELECT name, title, email FROM my_table');

foreach ($query->result() as $row)
{
        echo $row->title;
        echo $row->name;
        echo $row->email;
}

echo 'Total Results: ' . $query->num_rows();

The above result() function returns an array of objects. Example: $row->title

Standard Query With Multiple Results (Array Version)

$query = $this->db->query('SELECT name, title, email FROM my_table');

foreach ($query->result_array() as $row)
{
        echo $row['title'];
        echo $row['name'];
        echo $row['email'];
}
The above result_array() function returns an array of standard array indexes. Example: $row[‘title’]

Standard Query With Single Result

$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row();
echo $row->name;

The above row() function returns an object. Example: $row->name

Standard Query With Single Result (Array version)

$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row_array();
echo $row['name'];

The above row_array() function returns an array. Example: $row[‘name’]

Standard Insert

$sql = "INSERT INTO mytable (title, name) VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")";
$this->db->query($sql);
echo $this->db->affected_rows();

Query Builder Query

The Query Builder Pattern gives you a simplified means of retrieving data:

$query = $this->db->get('table_name');

foreach ($query->result() as $row) { echo $row->title; }

The above get() function retrieves all the results from the supplied table. The Query Builder class contains a full compliment of functions for working with data.

Query Builder Insert

$data = array(
        'title' => $title,
        'name' => $name,
        'date' => $date
);

$this->db->insert('mytable', $data);  // Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')

Use multiple databases in OpenCart

Use multiple databases in OpenCart

To use multiple databases in OpenCart (1.5.*), just update 3 files as given below:

  1. Config.php:
    Add:

     //New DB

    define(‘NEWDB_DRIVER’, ‘mysql’);
    define(‘NEWDB_HOSTNAME’, ‘localhost’);
    define(‘NEWDB_USERNAME’, ‘root’);
    define(‘NEWDB_PASSWORD’, ‘password’);
    define(‘NEWDB_DATABASE’, ‘sitename_newdb’);
    define(‘NEWDB_PREFIX’, ‘ndb’);
  2. Index.php:
    Below the current database setup ($db = new DB(DB_DRIVER …) add:

     $newdb = new DB(NEWDB_DRIVER, NEWDB_HOSTNAME, NEWDB_USERNAME, NEWDB_PASSWORD, NEWDB_DATABASE);

    $registry->set(‘newdb’, $newdb );
  3. system/database/mysql.php:
    Modify:

     change:

    if (!$this->link = mysql_connect($hostname, $username, $password)) {
    to:
    if (!$this->link = mysql_connect($hostname, $username, $password, true)) {

After these above steps we can access the new database by:

$this->newdb->query("SELECT * FROM ". NEWDB_PREFIX . "users");

multiple database connection in laravel

multiple database connection in laravel

.env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1 //database first
DB_DATABASE_OPENCART=database2    // database second
DB_USERNAME=root
DB_PASSWORD=aaaa@#2233

config/database

‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘localhost’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE’, ‘database1’),
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ‘aaaa@#2233’),
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => null,
],
‘opencart’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘localhost’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE_OPENCART’, ‘database2’),
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ‘aaaa@#2233’),
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => null,
],

In Controller file

$db_ext = DB::connection(‘opencart’);
$countries = $db_ext->table(‘fit_cart’)->get();
print_r($countries);

List of Sql Injection code strings

List of Sql Injection code strings

‘ or 1=1–

” or 1=1–

or 1=1–

‘ or ‘a’=’a

” or “a”=”a

‘) or (‘a’=’a

“) or (“a”=”a

advantages and disadvantages of amazon web services

advantages and disadvantages of amazon web services

The AWS bouquet of services includes the following:

  • Simple Storage Service – This covers archiving of application programs and data and online backup. The service is low cost, high speed and scalable.
  • CloudDrive – This lets users utilize web-connected devices to access and upload photos, music, documents, and videos. They can also use their devices to stream music.
  • RedShift – The service is designed for analytic workloads connecting with business intelligence tools and standard SQL based clients. It is a data warehouse service that handles petabyte-scale data.
  • CloudSearch – is used for the integration of customized search capabilities and is a scalable search service.
  • Mechanical Turk – This lets developers incorporate human intelligence in remote procedure calls. It is an application program interface (API) that uses a human network to carry out tasks that computers are not suitable for.
  • Dynamo Database – is a NoSQL database which is fully managed and known for its scalability and low latencies.
  • ElastiCache – is protocol-compliant with Memcached, which alleviates database load by speeding up dynamic web applications. Memcached is an open source and high performing distributed memory object caching system. ElastiCache is a fully managed caching service.
  • Elastic Compute Cloud – can be used as an unlimited number of virtual machines and lets business subscribers run app programs.

change password of phpmyadmin in ubuntu

change password of phpmyadmin in ubuntu

If you know your current password, you don’t have to stop mysql server. Open the ubuntu terminal. Login to mysql using:

mysql -u username -p

Then type your password. This will take you into the mysql console. Inside the console, type:

> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Then flush privileges using:

> flush privileges;

INSTALL LARAVEL ON UBUNTU 17.04 / 17.10 WITH APACHE2, MARIADB AND PHP SUPPORT

INSTALL LARAVEL ON UBUNTU 17.04 / 17.10 WITH APACHE2, MARIADB AND PHP SUPPORT

Laravel is a flexible and lightweight open source PHP framework with Model-View Controller (MVC) design pattern. It can be a great alternative to CodeIgniter framework. Laravel is designed for ease of use to allow developers create great applications.

If you’re looking for a simple and straightforward PHP framework to design your next application, you’ll find Laravel to be useful. This brief tutorial is going to show students and new users how to install Laravel PHP framework on Ubuntu 17.04 / 17.10 with Apache2, MariaDB and PHP support.

To get started with installing Laravel, follow the steps below:

Step 1: Install Apache2

Laravel requires a webserver to function and the second most popular webserver in use today is Apache2. So, go and install Apache2 on Ubuntu by running the commands below:

sudo apt install apache2

Next, run the commands below to stop, start and enable Apache2 service to always start up with the server boots.

sudo systemctl stop apache2.service
sudo systemctl start apache2.service
sudo systemctl enable apache2.service

Step 2: Install MariaDB

Laravel also requires a database server… and MariaDB database server is a great place to start. To install it run the commands below.

sudo apt-get install mariadb-server mariadb-client

After installing, the commands below can be used to stop, start and enable MariaDB service to always start up when the server boots.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service
sudo systemctl enable mariadb.service

After that, run the commands below to secure MariaDB server.

sudo mysql_secure_installation

When prompted, answer the questions below by following the guide.

  • Enter current password for root (enter for none): Just press the Enter
  • Set root password? [Y/n]: Y
  • New password: Enter password
  • Re-enter new password: Repeat password
  • Remove anonymous users? [Y/n]: Y
  • Disallow root login remotely? [Y/n]: Y
  • Remove test database and access to it? [Y/n]:  Y
  • Reload privilege tables now? [Y/n]:  Y

Restart MariaDB server

sudo systemctl restart mariadb.service

Step 3: Install PHP And Related Modules

Laravel is based on PHP.. so you’ll need to install it. To install PHP and related modules run the commands below

sudo apt install php libapache2-mod-php php-common php-mbstring php-xmlrpc php-soap php-gd php-xml php-mysql php-cli php-mcrypt php-zip

After install PHP, run the commands below to open PHP-FPM default file.

sudo nano /etc/php/7.1/apache2/php.ini           # Ubuntu 17.10
sudo nano /etc/php/7.0/apache2/php.ini           # Ubuntu 17.04

Then make the change the following lines below in the file and save.

memory_limit = 256M
upload_max_filesize = 64M
cgi.fix_pathinfo=0

Step 4: Install Composer To Download Laravel

Run the commands below to install composer package and install.. you must have curl package installed for the commands to work.. if not, just run sudo apt install curl to install it…

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Change into Laravel directory and run the commands below to download and install Laravel for th e project you want to create… name the project whatever you want… for this post, we’re calling it MyProject..

cd /var/www/html
sudo composer create-project laravel/laravel MyProject --prefer-dist

After running the commands above, a new project directory will be created… Run the commands below to set the correct permissions for that directory..

sudo chown -R www-data:www-data /var/www/html/MyProject/
sudo chmod -R 755 /var/www/html/MyProject/

Step 5: Configure Apache2

Finally, configure Apahce2 site configuration file for Laravel. This file will control how users access Laravel content. Run the commands below to create a new configuration file called laravel.conf

sudo nano /etc/apache2/sites-available/laravel.conf

Then copy and paste the content below into the file and save it. Replace the highlighted line with your own domain name and directory root location.

<VirtualHost *:80>   
  ServerAdmin admin@example.com
     DocumentRoot /var/www/html/MyProject/public
     ServerName example.com

     <Directory /var/www/html/MyProject/public>
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
     </Directory>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save the file and exit.

Step 6: Enable The Laravel And Rewrite Module

After configuring the VirtualHost above, enable it by running the commands below

sudo a2ensite laravel.conf
sudo a2enmod rewrite

Step 7: Restart Apache2

To load all the settings above, restart Apache2 by running the commands below.

sudo systemctl restart apache2.service



Then open your browser and browse to the server domain name. You should see Laravel page.

http://example.com

You should then see Laravel default home screen

Ubuntu 16.04 LTS – How To Install PHP, phpMyAdmin and MySQL

Ubuntu 16.04 LTS – How To Install PHP, phpMyAdmin and MySQL

Step 1 – Update repositories.

root@mail:/# apt-get update

root@mail:/# apt-get upgrade

Step 2 – Install mysql with the following command.

root@mail:/# apt-get install mysql-server mysql-client

Step 3 – You have to enter password for the root user.

Step 4 – You have to repeat password for the root user.

Step 5 – Install php7 for mysql with the following command.

root@mail:/# apt-get install php7-mysql

Step 6 – Install php7myadmin with the following command.

root@mail:/# apt-get install phpmyadmin

Step 7 – Choose web server who you want to use. i strongly recommended apache2

Step 8 – Configuring phpmyadmin – Configure database for phpmyadmin with dbconfig-common? write YES

Step 9 – Configuring phpmyadmin – Password of the database’s administrative user:

Step 10 – Configuring phpmyadmin – MySQL application password for phpmyadmin:

Step 11 – Configuring phpmyadmin – Password confirmation:

Step 12 – You have to write the ip address of your server “/” and phpmyadmin. You will phpMyAdmin.

Step 13 – You have to write password for the root user and login into phpmyadmin.

Step 14 – Restart apache service.

root@mail:/# service apache2 restart