Dorokhov.codes

07. Working with a database

For performing database operations WordPress provides a class wpdb which is present in the file - wp-includes\wp-db.php. This class abstracts the database functions for WordPress and most WordPress functions directly or indirectly use this class. We can create an object of this class to perform database operations but WordPress creates an object of this class during the load of WordPress.

This object is $wpdb and is a global object. So in case we want to perform any database operation we should use this global $wpdb object and call functions on them. By the help of $wpdb object we can perform all types of operations like in CRUD.

How to create a table in WordPress:

global $wpdb;

$table_name = $wpdb->prefix . 'chairs';

$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(255),
    min_weight INT,
    max_weight INT,
    min_height INT,
    max_height INT,
    image_url VARCHAR(255),
    badge_url VARCHAR(255),
    link VARCHAR(255),
    PRIMARY KEY (id)
)";

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

dbDelta( $sql );

How to remove a table:

global $wpdb;

$table_name = $wpdb->prefix . 'chairs';

$sql = "DROP TABLE IF EXISTS $table_name";

$wpdb->query($sql);

How to insert a row:

global $wpdb;

$table_name = $wpdb->prefix . 'your_table_name';

$data = array(
    'column1' => 'value1',
    'column2' => 'value2',
);

$wpdb->insert($table_name, $data);

Get records:

global $wpdb;

$table_name = $wpdb->prefix . 'chairs';

return $wpdb->get_results( "SELECT * FROM $table_name" );