The plugin generated x characters of unexpected output, $wpdb not defined

I’ve written a simple WordPress plugin to create a new database table.
The new table ought to be created when the plugin is activated.
When I try to activate the plugin, I get the following error:

The plugin generated 3989 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

emphasized text
This is obviously a result of the fact the $wbdb is not defined. xDebug outputs the following:

[Mon Feb 04 ] [error] PHP Notice:  Undefined variable: wpdb in test.php on line 13

The entire plugin consists of the following:

<?php

/**
 * Plugin Name: Test Plugin
 * Plugin URI: http://everybytcaptive.com
 * Description: A test plugin.
 * Version: 1.0
 * Author: Christopher Green
 * Author URI: http://everybytecaptive.com
 */

$test_db_name = $wpdb->prefix . 'test_db_name';

function test_install_plugin() {
    global $wpdb;
    global $test_db_name;

    $sql = "CREATE TABLE " . $test_db_name . " (
        `id` int(9) NOT NULL AUTO_INCREMENT,
        UNIQUE KEY id (id)
    );";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

register_activation_hook(__FILE__,'test_install_plugin');

?>

I have no other plugins installed.
Why isn’t $wpdb defined?
Is there a standard way to create a new database table when activating a plugin?

3 Answers
3

$wpdb is outside the scope of your plugin file, you need global $wpdb; before using $wpdb->prefix

Leave a Comment