Thursday, 13 February 2014

Custom Database Table with image upload plugin for wordpress

In this plugin we'll be looking at creating custom database tables and insert data into that table with custom image upload functionality . We'll cover how to create, maintain and remove the table, as well as how to safely, and efficiently, add, remove and query data along with custom image uploaded functionality.


WordPress provides "$wpdb" class using that we can interact with database like creating , maintain custom tables ,fetch data and insert data into database. 

  Download Custom Table Example.

Create Custom Table

function custom_table_example_install()
{
    global $wpdb;
    global $custom_table_example_db_version;

    $table_name = $wpdb->prefix . 'cte'; 

    
    $sql = "CREATE TABLE " . $table_name . " (
      id int(11) NOT NULL AUTO_INCREMENT,
      name tinytext NOT NULL,
      email VARCHAR(100) NOT NULL,
   image VARCHAR(255) NULL,
      age int(11) NULL,
      PRIMARY KEY  (id)
    );";

    // we do not execute sql directly
    // we are calling dbDelta which cant migrate database
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    // save current database version for later use (on upgrade)
    add_option('custom_table_example_db_version', $custom_table_example_db_version);
}
register_activation_hook(__FILE__, 'custom_table_example_install');

In the above code we create a function says "custom_table_example_install()" and call this function at the time of activation of the plugin by the help of "register_activation_hook()". In "custom_table_example_install()" function we declare sql query and exaecute that query by using "dbDelta()" .

When write sql to create your table remember following points:

  • each field MUST be in separate line
  • There must be two spaces between PRIMARY KEY and its name
    Like this: PRIMARY KEY[space][space](id)
    otherwise dbDelta will not work
After creating the database table we define "defining the custom table list".In this part we are define custom table list class,that will display our database records in nice looking table .




For download this plugin Click here.


No comments:

Post a Comment