This is one of my first attempts at querying the WordPress database for data, and some my first PHP code ever, so please bear that in mind when commenting.

It is supposed find data between two dates, and show it as HTML in a for each loop. How can this be made better? What is the correct way to query a WordPress database?

$sd = date('Y-m-d', strtotime(($startdate = filter_input(INPUT_GET, 'startdate'))));
$ed = date('Y-m-d', strtotime(($enddate = filter_input(INPUT_GET, 'enddate'))));
$query = $wpdb->prepare("SELECT FirstName, LastName, FROM WHEN HireDate BETWEEN '%s' and '%s'" $sd, $ed);
echo $query; 
$results = $wpdb->get_results( $query );
  • \$\begingroup\$ Welcome to the Code Review Community. It isn't quite clear what you are trying to improve, security, performance. We also do better reviews when there is more code. How do you process the results once you get them? \$\endgroup\$
    – pacmaninbw
    Commented Feb 27, 2021 at 12:13
  • \$\begingroup\$ I'm still learning PHP, and well, I realize this is bad code. I am looking for feedback as to how one accesses the wordpress database in general? Do you use the WPDB functions? Something else? \$\endgroup\$
    – ddk
    Commented Feb 27, 2021 at 12:53
  • \$\begingroup\$ I don't WP but this seems topical: ottodestruct.com/blog/2010/dont-include-wp-load-please \$\endgroup\$ Commented Feb 28, 2021 at 1:53
  • \$\begingroup\$ Why do you think it's a bad code? I am not a WP pro, but this code looks good from performance and security points of view. If you don't need WP but only need to access a database then there is no such a separate entity as a "wordpress database" and so there are no special tools either - you can use any tool available, from mysqli to Doctrine. \$\endgroup\$ Commented Mar 1, 2021 at 9:34

1 Answer 1


If you're working with a custom table you have within your database, which you use for WP, then using $wpdb is the way to go. Just remember to use prepare, if there's any user submitted stuff included in the query.

If on the other the data is stored as posts (with custom post type) with associated post meta, then WP_Query with meta_query argument is more appropriate way to find the data. (It uses $wpdb in the end, but is the more typical way to query posts).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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