In this article I will show you how you can create wordpress tables and also how to store data in wordpress tables. WordPress can be used to store arbitrary data(data not related to wordpress settings, posts/pages, profile, wordpress functionality etc).
What is WordPress Tables
WordPress tables are MySQL tables created using WordPress API and their name starts with WordPress defined prefix.
WordPress $wpdb global object
$wpdb global object is used to retrieve the prefix of wordpress tables, add rows to wordpress tables and get rows from wordpress tables.
Retrieving Prefix
For multisite wordpress installation prefix property returns different prefixes for each site in the network.
Adding Row
The insert method has 3 parameters, the table name, an array representing the row and the columns data format.
Retrieving Rows
Iterating Result
echo $row->name;
echo $row->ID;
}
dbDelta function
dbDelta function is used to create WordPress tables.
$sql = "CREATE TABLE $table_name (
id INT NOT NULL ,
name varchar(255) NOT NULL
);";
/*To use this function you must include it.*/
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
If the table exists then dbDelta will not create a table, it will just ignore.
Leave a Reply