Can I run multiple queries with $wpdb->prepare?

I have a query(actually multiple queries) that runs perfectly in phpmyadmin, (I’ve also tried get_var in place of get_results, but I think I might need an alternative to $wpdb->prepare. How can I run this all at once?

function myfunction( $campaign_id = 0 ) {
    global $wpdb;
    $coupon_code = $wpdb->get_results(  $wpdb->prepare( "SET @update_code := 0;
                UPDATE " . $wpdb->prefix . "my_table SET status = 1, code = (SELECT @update_code := code)
                WHERE campaign_id = %d AND status IS NULL LIMIT 1;
                SELECT @update_code as code;
                ",$campaign_id ) );
return $coupon_code->code;
}

Error

WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'UPDATE wp_my_table SET status = 1, code = (SELECT @update_code := code)' at line 2
for query: (runs perfectly in phpmyadmin)
SET @update_code := 0;
UPDATE wp_my_table SET status = 1, code = (SELECT @update_code := code)
WHERE campaign_id = 0 AND status IS NULL LIMIT 1;
SELECT @update_code as code;

1 Answer
1

Outside of subqueries, MySQL will only process 1 query at a time. When running sql statements through phpmyadmin, it just executes 1 query after the other. To do the same thing in WordPress, it appears you just use 1 query per $wpdb object (those can have subqueries if desired, but not what’s needed here).

Leave a Comment