3
\$\begingroup\$

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?

<?php 
require_once('wp-load.php');
$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 );
?>
\$\endgroup\$
4
  • \$\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 Feb 27 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 Feb 27 at 12:53
  • \$\begingroup\$ I don't WP but this seems topical: ottodestruct.com/blog/2010/dont-include-wp-load-please \$\endgroup\$ – mickmackusa Feb 28 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\$ – Your Common Sense Mar 1 at 9:34
1
\$\begingroup\$

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).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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