php - database not creating and giving error on plugin activation
I am new to development so any feedback is appreciated - i have built a wordpress plugin that needs to create a new database table on plugin activation. When I activate the plugin i get the following error, and the new table has not been created.
'The plugin generated 1050 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.'
Here's the code:
global $ed_wp_cardealer_db_version;
$ed_wp_cardealer_db_version = '1.0';
//create database table
function create_database(){
global $wpdb;
global $ed_wp_cardealer_db_version;
$table_name = $wpdb->prefix . 'ed_wp_cardealer';
$charset = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
valuation_id int NOT NULL AUTO_INCREMENT,
vrm TINYTEXT,
price int(9),
vehicleDescription TINYTEXT,
email TINYTEXT,
PRIMARY KEY (valuation_id)
)$charset;";
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
dbDelta( $sql );
add_option( 'ed_wp_cardealer_db_version', $ed_wp_cardealer_db_version );
}
//create database on plugin activation
register_activation_hook( __FILE__, 'create_database' );
I've checked it over and over against the wordpress official docs and can't see any obvious errors. If I activate the plugin without this line then there is no error, but the database is still not created
register_activation_hook( __FILE__, 'create_database' );
I have seen lot's of responses to similar queries that suggest removing extra space from opening php tag etc, but I need to create the new table as well as remove the error.
I have set debug to true in wp-config, but can't see any further details than i have given.
Answer
Solution:
I change valuation_id int value length. When you declare int value in DB must assign int length. Also, add two extra parameters on add_option.
Please try the below code hopefully work it. I test it on my local development server.
global $ed_wp_cardealer_db_version;
$ed_wp_cardealer_db_version = '1.0';
//create database table
function create_database(){
global $wpdb;
global $ed_wp_cardealer_db_version;
$table_name = $wpdb->prefix . 'ed_wp_cardealer';
$charset = $wpdb->get_charset_collate();
$sql = " CREATE TABLE $table_name (
valuation_id int(11) NOT NULL AUTO_INCREMENT,
vrm TINYTEXT,
price int(9),
vehicleDescription TINYTEXT,
email TINYTEXT,
PRIMARY KEY ( valuation_id )
)$charset;";
require_once( ABSPATH . "wp-admin/includes/upgrade.php" );
dbDelta( $sql );
add_option( 'ed_wp_cardealer_db_version', $ed_wp_cardealer_db_version, '', 'yes' );
}
//create database on plugin activation
register_activation_hook( __FILE__, 'create_database' );
Screenshot:
Source