I am working on a plugin the needs to create a database and insert data into it, I have the table creating part done, but there is an error whenever I try and use $wpdb
to insert data saying that insert() could not be called on a null object
.
Here is a minimal version:
<?php
/*
Plugin Name: Test
*/
function activation() {
global $wpdb;
$table_name = $wpdb->prefix . 'testing';
$charset_collate = $wpdb->get_charset_collate();
# create table
if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
$sql = "CREATE TABLE " . $table_name . " (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name TEXT NOT NULL,
PRIMARY KEY (id)
) " . $charset_collate . ";";
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
dbDelta($sql);
}
}
function html($atts) {
$out = "";
return "<form action='wp-content/plugins/test/submit.php' method='post'><input type='text' name='name'><input type='submit' name='submit'></form>";
}
# setup and cleanup hooks
register_activation_hook(__FILE__, "activation");
add_shortcode('testing', 'html');
Here is the form submit file:
<?php
function handle() {
global $wpdb;
if (isset($_POST['submit'])) {
$wpdb->insert('wp_testing', array('name' => "test"));
}
}
handle();
I read this question: $wpdb is null even after 'global $wpdb and it is pretty unclear, but seems to indicate that $wpdb
must be used within a function, so I wrapped it in one. Any ideas on why this is?