问题
I'm currently writing a plugin for a customer, and while it's usually working good, I found that dbDelta does not allow me to create the table I need on plugin activation.
I'm running the below code to bind the activation function:
register_activation_hook(__FILE__, 'adminInstallation');
And this is the function itself:
function adminInstallation(){
global $wpdb;
$objectEquipment = 'wp_object_equipment';
$equipmentSQL = "CREATE TABLE ".$objectEquipment." (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name tinytext NOT NULL
);";
require_once(ABSPATH.'wp-admin/includes/upgrade.php');
$equipment = dbDelta($equipmentSQL);
}
Once this has been run, I am checking the database, but no tables have been added. Trying to dump the error will only result in Wordpress telling me there was unexpected output, but it wont let me see the actual message that the server returns. This issue has been bugging me for some hours, and I cant continue until it's solved. Does anyone here have any idea why it might do this?
As far as I can tell, all the code is valid, and this is the third plugin I've written. I even tried using the code from my previous ones, but that did not work either.
EDIT: I tried running the function after the plugin activation and dump the dbDelta response. It reports that the table has been created, but still, there's nothing new in the database. Any ideas?
Thanks in advance! // Jonathan
回答1:
From http://codex.wordpress.org/Creating_Tables_with_Plugins:
- You have to put each field on its own line in your SQL statement.
- You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
- You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.
回答2:
You shoud echo $wpdb->last_error;
after dbDelta call so you get the mysql error.
回答3:
I do know that dbDelta is very particular about the formatting. I believe the issue is that you are not using backticks (`) around database parts. Try the following.
On a side note, wouldn't hurt to designate a primary key.
$equipmentSQL = "CREATE TABLE `".$objectEquipment."` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`name` tinytext NOT NULL,
PRIMARY KEY (`id`)
);";
回答4:
You can try this function:
$table_name = "ratings";
$table_columns = "id INT(6) UNSIGNED AUTO_INCREMENT,
rate tinyint(1) NOT NULL,
ticket_id bigint(20) NOT NULL,
response_id bigint(20) NOT NULL,
created_at TIMESTAMP";
$table_keys = "PRIMARY KEY (id),
KEY ratings_rate (rate),
UNIQUE KEY ratings_response_id (response_id)";
create_table($table_name, $table_columns, $table_keys);
回答5:
I search and dbDelta is running $wpdb->query($sqlQuery); for custom queries.
For those whose dbDelta is not working use
dbDelta($sql_query_to_create_table);
Thanks! Have a nice code
来源:https://stackoverflow.com/questions/7230021/wordpress-dbdelta-not-functioning