Wordpress list results from wp_users and wp_usermeta - mysql

I am writing a plugin which grabs an array of data from the wordpress database using...
$data = $wpdb->get_results("SELECT * FROM $wpdb->users", ARRAY_A);
This works fine and I can display all the info from the users table, the issue I have is that I need to also pull out the First name and Last name which are in the wp_usermeta table.
Is there a way to modify the statement to also pull those details from the other table?

Not in one query and not necessarily the slickest either, but the following will produce what you want:
$data = $wpdb->get_results("SELECT * FROM $wpdb->users", ARRAY_A);
$i = 0;
foreach($data as $single) {
$meta = $wpdb->get_results(
"SELECT meta_value
FROM $wpdb->usermeta
WHERE user_id = $single[ID]
AND (meta_key = 'first_name' OR meta_key = 'last_name')
ORDER BY meta_key",
ARRAY_A
);
$data[$i]['first_name'] = $meta[0]['meta_value'];
$data[$i]['last_name'] = $meta[1]['meta_value'];
$i++;
}
EDIT: Here it is in one query:
$data = $wpdb->get_results(
"SELECT $wpdb->users.*,
GROUP_CONCAT(
$wpdb->usermeta.meta_value
ORDER BY $wpdb->usermeta.meta_key
SEPARATOR ' '
) AS name
FROM $wpdb->users
LEFT JOIN $wpdb->usermeta
ON $wpdb->users.ID = $wpdb->usermeta.user_id
WHERE ($wpdb->usermeta.meta_key = 'first_name'
OR $wpdb->usermeta.meta_key = 'last_name')
GROUP BY $wpdb->users.ID",
ARRAY_A
);
Note that opposed to the first version, the latter does not produce $data[x]['first_name'] and $data[x]['last_name'], but $data[x]['name'] instead. This is due to either being stored in the "meta_value" column. It is not possible to accomplish your task in one query and store the first and last name in two different array keys at the same time.
Hence, if doing it the second way, you'd have to use php's explode() function later on to access the name. Or correct it in a loop after the query has been run:
$i = 0;
foreach($data as $single) {
$name_parts = explode(' ', $single['name']);
$data[$i]['first_name'] = $name_parts[0];
$data[$i]['last_name'] = $name_parts[1];
$i++;
}

Related

Copy only unique entries from one table to another MySQL

I'm trying to create scheduled auto-updater for MySQL DB. The script I use is shown below. It's idea is to insert only unique products from table wp_posts to table export_copy. But this one inserts nothing.
Please help me to fix the script.
INSERT INTO `export_copy`(`name`, `link`)
SELECT p.post_title, p.guid
FROM wp_posts p
WHERE NOT EXISTS (
SELECT *
FROM export_copy, wp_posts
WHERE export_copy.id=wp_posts.ID)
Your query will never work!
Since your table's name is "wp_posts" ,it seem you want copy data from wordpress table to your own
you can handle this by php, firt you must fetch data from table and save that to an array, then export array to insert query
$link = mysqli_connect(Your_HOST , Your_User , YOUR_Pass, DB_NAME);
$q = "SELECT p.post_title, p.guid FROM wp_posts p WHERE NOT EXISTS ( SELECT * FROM export_copy, wp_posts WHERE export_copy.id=wp_posts.ID)";
$result = mysqli_query($link, $q);
$i=0;
while($row=mysqli_fetch_assoc($result))
{
$a[$i]['name'] = $row['post_title'];
$a[$i]['link'] = $row['post_title'];
$i++;
}
$q = '';
foreach($a as $a)
$q .= "('".$a['name']."','".$a['link']."'),";
$q = substr($q,0, (strlen($q)-1));
$q = "INSERT INTO `export_copy`(`name`, `link`) VALUES " . $q;
$result = mysqli_query($link, $q);

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

SQL - SELECT with WHERE statement return false despite present field in table

I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";

Writing a custom mysql query to order wordpress users by a custom user meta field

Basically, I need to order a list of WordPress users by the city they live in. I've got a custom user meta field for city, and I've got the query working properly, but the query lists everyone who hasn't filled out a city at the beginning since it places blank fields at the beginning of the order.
What I need is to figure out how to only select and display users who have given a value other than blank in the city field. Unfortunately, I've found myself stumped.
Any thoughts on how to do this? Also, if anyone knows a way to orderby a custom user meta field using wp_user_query as opposed to this mess, I'm all ears.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$limit = 10;
$offset = ($paged - 1) * $limit;
$key = 'city';
$sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->users}.* FROM {$wpdb->users}
INNER JOIN {$wpdb->usermeta} wp_usermeta ON ({$wpdb->users}.ID = wp_usermeta.user_id)
INNER JOIN {$wpdb->usermeta} wp_usermeta2 ON ({$wpdb->users}.ID = wp_usermeta2.user_id)
WHERE 1=1
AND wp_usermeta.meta_key = 'wp_capabilities'
AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%\"subscriber\"%'
AND wp_usermeta2.meta_key = '$key'
ORDER BY wp_usermeta2.meta_value ASC
LIMIT $offset, $limit";
$site_users = $wpdb->get_results($sql);
$found_rows = $wpdb->get_var("SELECT FOUND_ROWS();");
foreach ($site_users as $site_user) {
// user info here
}
Try something like
...
WHERE 1=1
AND wp_whatever.name_of_city IS NOT NULL
AND LENGTH(wp_whatever.name_of_city) > 0
AND wp_usermeta.meta_key = 'wp_capabilities'
...

how can I connect these two tables in sql?

i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!