Return to Snippet

Revision: 44718
at April 16, 2011 05:41 by prwhitehead


Initial Code
function create_stats(){
	global $wpdb;
	
	//create the name of the table including the wordpress prefix (wp_ etc)
	$search_table = $wpdb->prefix . "stats";
	//$wpdb->show_errors(); 
	
	//check if there are any tables of that name already
	if($wpdb->get_var("show tables like '$search_table'") !== $search_table) 
	{
		//create your sql
		$sql =  "CREATE TABLE ". $search_table . " (
					  stat_id mediumint(12) NOT NULL AUTO_INCREMENT,
					  business_id mediumint(9),
					  time VARCHAR (20) NOT NULL, 
					  user_ip text(20) NOT NULL,
					  user_id mediumint(9),
					  user_browser text NOT NULL,
					  referral_page text NOT NULL,
					  type text,
					  UNIQUE KEY stat_id (stat_id));";
	}
	
	//include the wordpress db functions
	require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
	dbDelta($sql);
	
	//register the new table with the wpdb object
	if (!isset($wpdb->stats)) 
	{
		$wpdb->stats = $search_table; 
		//add the shortcut so you can use $wpdb->stats
		$wpdb->tables[] = str_replace($wpdb->prefix, '', $search_table); 
	}
}

//add to front and backend inits
add_action('init', 'create_stats');

Initial URL

                                

Initial Description
Create custom database tables within wordpress. Just replace 'stats' with the name of your table, and then the $sql variable with your create table sql.

Initial Title
Wordpress: Create custom database tables

Initial Tags
database, php, table, wordpress

Initial Language
PHP