Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm creating a plugin and I want to automate the creation of a MySQL Trigger on a table. The problem seems to be that $wpdb->query doesn't appear to accept either multipart statements and/or formatted queries.

If I print and run the following query in phpMyAdmin it returns success. I also noticed if I formatted the query all on 1 line it would still report success but in this case the trigger is NOT created.

$wpdb->query(
    "DELIMITER //
    DROP TRIGGER IF EXISTS {$wpdb->get_blog_prefix($site->id)}post_queue_insert//
    CREATE TRIGGER {$wpdb->get_blog_prefix($site->id)}queue_insert BEFORE INSERT ON {$wpdb->get_blog_prefix($site->id)}posts
    FOR EACH ROW BEGIN
        INSERT INTO {$wpdb->base_prefix}post_queue (action_id, action_type, action_status, action_timestamp, sync_complete, SITE_ID) VALUES (NEW.ID, NEW.post_type, NEW.post_status, UNIX_TIMESTAMP(now()), 0, {$site->id});
    END//
    DELIMITER ;"
);

Is there another function I can use or another way to format the query to run successfully?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

After much trial and error I finally figured out a solution using mysqli. I consider it a acceptable solution since the query will only be run on plugin updates.

$mysqli = new mysqli();
$mysqli->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$sql = "
    DROP TRIGGER IF EXISTS {$wpdb->get_blog_prefix($site->id)}post_queue_insert;
    CREATE TRIGGER {$wpdb->get_blog_prefix($site->id)}post_queue_insert BEFORE INSERT ON {$wpdb->get_blog_prefix($site->id)}posts
    FOR EACH ROW BEGIN
        INSERT INTO {$wpdb->base_prefix}post_queue (action_id, action_type, action_status, action_event, action_timestamp, sync_complete, SITE_ID) VALUES (NEW.ID, NEW.post_type, NEW.post_status, 'insert', UNIX_TIMESTAMP(now()), 0, {$site->id});
    END;
";

$mysqli->multi_query($sql);
$mysqli->close();
share|improve this answer
    
Exactly what I was looking for. Thanks @EddyR! –  MathSmath Jan 10 '12 at 19:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.