Using Database

This section will explain how to interact with database and you can create tables or upgrade plugin database e.t.c

# db()

The db()  return you the mysqli resource that you can use to make query to the database . For example

$query = db()->query("SELECT * FROM users");

With that you can INSERT , UPDATE or DELETE from database

How to create tables

Actually you can create a table right from your PHPmyadmin but there will be a next question how will you distribute the plugin with the tables, here come the solution

1. Create a folder call database/ in your plugin

2. create two files install.php and upgrade.php this two file will be called during installation of the plugin and updaing of the plugin respectively.

Install.php

Inside the install.php file create a function like the one below

<?php 
function test_install_database() {
//your query execution codes here
}

Note the test in bold , it is your plugin name and this function will be call when user install your plugin and you can use it to create tables , dump data into your tables e.t.c

For exmple

 db()->query("CREATE TABLE IF NOT EXISTS `test_talbe` (
      `id` varchar(255) NOT NULL,
      `active` int(11) NOT NULL DEFAULT '1',
      UNIQUE KEY `id` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

 Upgrade.php

This is called when user click on the update plugin in the plugin manager section and the function is simlar to install.php as you see below 

 

<?php 
function test_upgrade_database() {
//your query execution codes here
}

And your query code will be inside as described in the install.php, you can actually use this to add columns or remove columns e.t.c 

 

Thanks for reading