Question

I want to know that is it possible to fire a stored procedure once the plugin is activated?

//action hook for plugin activation
register_activation_hook( __FILE__, 'my_func' );

//function to create stored procedure
function my_func()
{
//code goes here to create a stored procedure
}

Any help would be appreciated. Thank you.

No correct solution

OTHER TIPS

As an example, let's say you were planning on the following stored procedure:

SELECT * FROM wp_posts

Instead of actually stashing this inside MySQL, let's create a PHP function:

function {plugin_prefix}_get_posts() {
    global $wpdb;

    return $wpdb->get_results( "SELECT * FROM $wpdb->posts" );
}

Now we can call this whenever we need it:

$posts = {plugin_prefix}_get_posts();
// Away we go!

I've intentionally used invalid PHP to save the future copy-pasters from themselves - rename the function to something specific to your project!

Yes it is possible, on plugin activation you just need to call the relevant mysql queries via the php api as documented in the manual http://php.net/manual/en/mysqli.quickstart.stored-procedures.php, and remove on deactivation.

Is it smart? I am far from being a mysql guru, but it seems like @thedeadmedic is right about doing simple things like selects. Performance of such things depends on the complexity of the data and you save nothing by reducing the size of the request. Stored procedures has an advantage only if it can reduce the amount of data which travels from the DB to PHP.

Another two things to remember in the context of general plugins.

  1. Stored procedures are global to the DB and not unique to a specific WP instance, therefor they need to be written carefully to both not collide with other stored procedure, and from security POV, not to leak data.

  2. At the time of writing this answer there are about 7% of wordpress users that run on mysql versions that do not support them (versions older than 5.5).

Just do it in the activation hook using $wpdb->query() and make sure to prefix it properly.

public static function activation_hook() {
    global $wpdb;
    $sql = "
    CREATE PROCEDURE {$wpdb->prefix}STORED_PROC_NAME(param1 varchar(16))
    RETURNS varchar(16)
    BEGIN
       --do your stored proc here
       RETURN param1
    END
    ";
    $wpdb->query($sql);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top