WordPress环境下MariaDB SQL语法错误问题求助
Got it, let's break down the issue with your database query and get it working again.
First, the immediate syntax error comes from a small but critical mistake in your WHERE clause. You wrote:
$wpdb->posts.post_status = IN ('publish', 'future')
Combining the equality operator (=) with the IN operator is invalid SQL. The IN operator already checks if a value matches any item in the provided list, so the = is completely redundant here—and it's what's triggering that syntax error.
Fixed Query (Plus a Security Upgrade)
I've corrected that issue and also added a critical security improvement (using $wpdb->prepare() to avoid SQL injection risks, which you should always do when inserting variables into queries):
// Check if there are posts before our $date $postA = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date FROM {$wpdb->prefix}posts LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE $wpdb->posts.post_status IN ('publish', 'future') AND $wpdb->posts.post_type = 'post' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id = 18 AND $wpdb->posts.post_date < %s ORDER BY post_date DESC LIMIT 1", $date ) );
Key Changes Made:
- Removed the extra
=beforeINfor thepost_statuscheck to resolve the syntax error. - Replaced the direct
'{$date}'insertion with%sin the query string, paired with$wpdb->prepare()to safely pass the$datevariable. This prevents SQL injection attacks, which is a must for WordPress database interactions. - Fixed a minor typo in the comment ("is posts" → "are posts") for clarity.
Quick Additional Checks:
If you still run into issues after applying this fix, verify two more things:
- Ensure
$dateis formatted correctly for MariaDB (valid formats includeYYYY-MM-DDorYYYY-MM-DD HH:MM:SS). - Confirm that term ID
18actually exists in yourwp_term_taxonomytable and is associated with thecategorytaxonomy.
内容的提问来源于stack exchange,提问作者user6677795

