Create a table in the database using code in WordPress.

Code to create a database table dynamically using PHP.

// Register the table creation function to run when the plugin or theme is activated.
register_activation_hook(__FILE__, 'create_custom_table');

// Function to create the custom table.
function create_custom_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'custom_images';
    $database = 'nextdatabase';

    // Define the SQL for table creation.
    $sql = "CREATE TABLE IF NOT EXISTS $database.$table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        image_data longblob NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

    // Include WordPress upgrade.php for dbDelta function.
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    // Create or update the table in the database.
    dbDelta($sql);
}

Add this code to function.php or php file in plugin.

Leave a comment

Your email address will not be published. Required fields are marked *