kwh71787
kwh71787

Reputation: 576

$wpdb->query Wordpress shortcode causing syntax error

I'm trying to update numerous wordpress multisite pages. I have an ajax script that is posting to a php file where, after the text is formatted, it updates the corresponding table cell.

However, I keep getting the "WordPress database error You have an error in your SQL syntax;" error.

$content = "[shortcode] text processed by shortcode [/shortcode]";
$table = "wp_".$_POST["blogid"]."_posts";
$wpdb->query(" UPDATE {$table} SET post_content={$content} WHERE posts_title='test'");

Is this an issue with the use of square brackets (shortcodes) in the string I wish to use to update the cell?

The syntax seems fine to me, but my SQL knowledge isn't that strong. In greater detail, I have a mysql query that gets all multisites, then loops through them after making the edits with JS before posting to this php file.

Upvotes: 0

Views: 212

Answers (1)

Josh from Qaribou
Josh from Qaribou

Reputation: 6908

Avoid using string templates directly for query building. You can too-easily include invalid syntax, and since you're reading content directly from the shortcode you're opening your entire database up to SQL-injection attacks. This could give attackers direct access to your database, meaning anyone who can post content could also gain total access to your WordPress.

Always prepare your query first. If you're using $wpdb, the usage is described here: https://developer.wordpress.org/reference/classes/wpdb/prepare/

This will also ensure that the shortcode content you query on is formatted properly.

Upvotes: 1

Related Questions