Create a custom table and insert a row with $wpdb

Description: Create a table wp_tc_visits with the columns id, page and hits. Insert the row (home, 10), and read it back with a prepared query.

Hint:

  • Use $wpdb->prefix, dbDelta(), $wpdb->insert() and $wpdb->prepare().

Solution

global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';

$table   = $wpdb->prefix . 'tc_visits';
$charset = $wpdb->get_charset_collate();

dbDelta( "CREATE TABLE $table (
	id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	page varchar(100) NOT NULL,
	hits int(11) NOT NULL DEFAULT 0,
	PRIMARY KEY  (id)
) $charset;" );

$wpdb->insert( $table, array( 'page' => 'home', 'hits' => 10 ), array( '%s', '%d' ) );

$row = $wpdb->get_row( $wpdb->prepare( "SELECT page, hits FROM $table WHERE page = %s", 'home' ) );
echo $row->page . ' => ' . $row->hits;
Output

home => 10

How it works

  • dbDelta() creates the table (and it would update it if it existed).
  • insert() writes the row and prepares the values with the formats %s and %d.
  • prepare() protects the select query from SQL injection.

Read WordPress $wpdb.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.