fellow coders! I an having a hard time JOIN(ing) tables.

I have a a lot of users on my site and many of them have the same last names. I am trying to get their emails by their last name. WP stores emails in the users table and user names in the usermeta and I have been trying to use JOIN to get what I want, but I don’t understand how it works and I am about to give up for the day.
This is what i have after 4.5 hours.

$usersemails = $wpdb->get_results("SELECT users.user_email, usermeta.meta_value 
FROM $wpdb->users
LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id 
    WHERE user_status="0" 
    AND meta_value="Smith"");

Any help is appreciated, so can you please help? Thanks.

3 Answers
3

Hi @Holidaymaine:

Not sure where you are doing wrong, but try the following instead which is a self contained test.php file you can drop into the root of your website and load in your browser with http://yoursite.com/test.php (assuming you replace yoursite.com with your site’s domain! Also, note how I adding in a WHERE {$wpdb->usermeta}.meta_key = 'last_name' to ensure you did not get records you were not expecting):

<?php
/*
Filename: test.php
*/

include('wp-load.php');

$sql =<<<SQL
SELECT
  {$wpdb->users}.user_email,
  {$wpdb->usermeta}.meta_value
FROM
  {$wpdb->users}
  LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb->usermeta}.user_id
WHERE 1=1
  AND {$wpdb->users}.user_status="0"
  AND {$wpdb->usermeta}.meta_key = 'last_name'
  AND {$wpdb->usermeta}.meta_value="Smith"
SQL;
  $usersemails = $wpdb->get_results($sql);
  header('Content-type:text/plain');
  print_r($usersemails);

Leave a Reply

Your email address will not be published. Required fields are marked *