WordPress SQL Query – meta_value date saved as string issues in php file – works in phpmyadmin

huangapple go评论95阅读模式
英文:

WordPress SQL Query - meta_value date saved as string issues in php file - works in phpmyadmin

问题

  1. $query = $wpdb->prepare("SELECT post_id
  2. FROM {$wpdb->prefix}postmeta t1
  3. WHERE meta_key = 'expiry_date'
  4. AND STR_TO_DATE(meta_value, '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 6 MONTH
  5. AND EXISTS (SELECT 1 FROM wp_postmeta t2
  6. WHERE t2.meta_key = 'customer_email'
  7. AND t2.meta_value = %s
  8. AND t2.post_id = t1.post_id)
  9. GROUP BY post_id", 'test@hotmail.co.uk');
  10. $result = $wpdb->get_results($query, ARRAY_A);
  11. $result returns empty because of this:
  12. AND STR_TO_DATE(meta_value, '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 6 MONTH
  13. meta_value column saves the date as a string hence I need to use STR_TO_DATE.
  14. This query FULLY WORKS when I run it in phpmyadmin but not in my php wordpress file.
  15. It only works inside my php file when I remove the line of code above.
英文:
  1. $query = $wpdb->prepare("SELECT post_id
  2. FROM {$wpdb->prefix}postmeta t1
  3. WHERE meta_key = 'expiry_date'
  4. AND STR_TO_DATE(meta_value, '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 6 MONTH
  5. AND EXISTS (SELECT 1 FROM wp_postmeta t2
  6. WHERE t2.meta_key = 'customer_email'
  7. AND t2.meta_value = %s
  8. AND t2.post_id = t1.post_id)
  9. GROUP BY post_id", 'test@hotmail.co.uk');
  10. $result = $wpdb->get_results( $query, ARRAY_A );

$result returns empty because of this:

  1. AND STR_TO_DATE(meta_value, '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 6 MONTH

meta_value column saves the date as a string hence I need to use STR_TO_DATE.

This query FULLY WORKS when I run it in phpmyadmin but not in my php wordpress file.
It only works inside my php file when I remove the line of code above.

答案1

得分: 1

使用'%%Y-%%m-%%d'解决了这个问题。谢谢

英文:

@anyber Using '%%Y-%%m-%%d' solved this issue. Thanks

huangapple
  • 本文由 发表于 2023年2月8日 20:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定