I'm building a WordPress website.
With a MySql Query I load all companies from my database that have a specific brand:
$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'brand'")`
brand is an array so I search for a specific value in array:
$brand = $_GET['brand'];
$brandNeedle = $brand;
if(in_array($brandNeedle, $brand[0]))
Now, my client asked to list all users that are connected to all those companies that are selected.
So I need to create a new query. Fortunately the users all have a field added to their colum that tells me where they are working.
So I thought: what if I create a array that holds all companynames that are queried from the companylist.
With this array I can select all users who have the company name in their column
So I think the query should be something like this:
SELECT * FROM $wpdb->usermeta WHERE meta_key='company' AND meta_value ='THE ARRAY'
But this doesn't work obvious because it can't search with an array in an array.
I can't seem to figure it out. Any ideas?
-- EDIT --
Okay so I did the implode function and I do something wrong:
$brand_array = array();
for($i=0; $i <count($results); $i++){
$result = $results[$i];
if ($i % 2 == 0){
$oddeven = 'even';
}else{
$oddeven = 'odd';
}
$post_id = $result->post_id;
$company_name = get_post_meta($post_id, 'company_name', true);
$brand_array[] = $company_name;
}
print_r($brand_array);
$imploded = implode(',',$brand_array);
$query = "SELECT * FROM $wpdb->usermeta WHERE meta_key='company' AND meta_value IN $imploded";
$persons = $wpdb->get_results($query);
This gives me the results I need (the two companies in a new array)
and gives me the following error:
WordPress database error: [You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'brand1,brand2' at line 1]
SELECT * FROM wp_usermeta WHERE meta_key='company' AND meta_value IN
brand1,brand2
Have you thought about using the "IN" clause on MySQL?
https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in
You would probably have something like:
$query = "SELECT * FROM ".$wpdb->usermeta." WHERE meta_key='company' AND meta_value IN ('".implode("', ', $brand)."')";
(edit: forgot to add the parenthesis around the "in" content)
Search for mysql for IN clause
SELECT * FROM $wpdb->usermeta WHERE meta_key='company' AND meta_value IN implode(',',$brand_array)
Related
I have a code in PHP where I want to display multiple times values, and so, even if these values are the same between them. My code is simple :
$sql = "SELECT photo from table WHERE username IN ('1','2','2') ORDER BY id DESC ";
$res = array();
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
array_push($res, $row['photo']);
}
echo json_encode($res);
But this code only display (in json) an array of two values (because the values of photo of the username 2 are the same).
What I want to achieve is to make an array with the exact same number of values of the number of username I defined WHERE username IN ('1','2','2') (so here, 3 values).
I hope you understood me, thanks for helping me !
I think what you're after is to list even the duplicates in the end result. As your SQL will only retrieve the unique items, the idea would be to include the username in the SQL result set. Then use the original list of user names ($userNames) and add in the photo for each of them.
I've used mysqli_fetch_all() to simplify the process of fetching all of the data, then used array_column() to make the username the key for the photos.
$userNames = array(1,2,2);
$sql = "SELECT username, photo
from table
WHERE username IN ('".implode("','", $userNames)."')
ORDER BY id DESC ";
$res = array();
$result = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($result, MYSQLI_ASSOC);
$photos = array_column($photos, "photo", "username");
foreach ( $userNames as $user ) {
if ( isset($photos[$user])) {
$res[] = $photos[$user];
}
else {
$res[] = '';
}
}
echo json_encode($res);
You would use left join:
select t.photo
from (select '1' as username union all select '2' union all select '3'
) u left join
table t
on t.username = u.username
order by t.id desc;
Note this will return rows, even when the user name does not exist. If you want to filter those rows, remove the left so you are doing an inner join.
postmeta table example
The end result is matching an array of 'post_id', sorted by the number of attendees. I know it is a WP backend but I have to do it in SQL, no 'get_posts' or anything WordPress related. What I'm wanting to do is confusing so I'll try to be clear.
What I Have To Begin:
$check_post_ids - the original array of post_ids I need to check
$start_date - the 'meta_value' each event's '_StartDate' needs to match.
What I Need To Do:
I need to check these three post_ids to see if they have a matching start date. If they do, I need to get an array of post_ids sorted from the highest to lowest number of attendees.
Currently I was planning on doing this with multiple SELECTs and foreach() statements, but I feel like there has to be a simpler way to do this ( i.e. One SELECT & foreach() ). Here's what I'm doing at the moment. I haven't finished it yet because I feel like there has to be a simpler way to do this. Newer to SQL and any help is tremendously appreciated!
$check_post_ids = array('484', '627', '982', '2435');
$start_date = '1963-10-20 19:30:00';
// iterate through array of post_ids and check if they have the same _StartDate
foreach($check_post_ids as $id){
$start_date_check = "SELECT * FROM `wp_postmeta` WHERE `post_id` =" . $id . " AND `meta_key` LIKE '_StartDate' AND `meta_value` = '" . $start_date . "'";
$start_date_check_result = mysqli_query($conn, $start_date_check);
// assign all post_ids with a matching _StartTime to a new array
if (mysqli_num_rows($start_date_check_result) > 0) {
while($row = mysqli_fetch_assoc($start_date_check_result)) {
$matching_post_ids[] = $row['post_id'];
// iterate through matching_post_ids array, get the _NumAttendees for each, and assign their id and _NumAttendees to an assoc array to be sorted
foreach($matching_post_ids as $id){
$attendees_check = "SELECT meta_value FROM wp_postmeta WHERE post_id = " . $id . " AND meta_key = '_ecp_custom_2'";
$attendees_check_result = mysqli_query($conn, $attendees_check);
if($upvotes_check > 0){
while($row = mysqli_fetch_assoc($attendees_check_result)){
$sort_by_attendees['id'] = $id;
$sort_by_attendees['attendees'] = $row['meta_value'];
$sort_by_attendees_array[] = $sort_by_attendees;
}
}
}
For the first part of the query, I think you can simplify your code by using SQL IN keyword. Basically it substitutes the role of your first array with all your post IDs. Then, you can write a SQL query like this :
SELECT meta_value
FROM wp_postmeta
WHERE meta_key = '_ecp_custom_2'
AND post_id IN (SELECT post_id
FROM wp_postmeta
WHERE post_id IN ('484', '627', '982', '2435')
AND meta_key LIKE '_StartDate'
AND meta_value = '" . $start_date . "'")
ORDER BY meta_value DESC
There are 2 queries. The first one in the parenthesis, subselect all the post ids on your table wp_postmeta where post_ids have ids in your list and if they match with your starting date. Then, the main query selects all meta_values (I suppose attendees) based on your first subquery (all post ids with your starting date).
Hope it will help you.
I have a query that loads values from the database based upon a province a user lives:
$query = "SELECT * FROM $wpdb->usermeta WHERE meta_key='provincie' AND ( ".$provincie_check.")";
This loads all provinces that a user holds.
Based upon this I load the users:
for($p=0; $p <count($personen); $p++){
$persoon = $personen[$p];
if ($p % 2 == 0){
$oddeven = 'even';
}else{
$oddeven = 'odd';
}
$id = $persoon->user_id;
$user_info = get_userdata($id);
$p_fname = get_user_meta($id, 'first_name', true);
$p_fname = array($p_fname);
sort($p_fname);
}
For every user I create a table to view them. I want them sorted upon ther first name. So I thought I create an array of all first names and sort that.
But no luck.
How can I sort the for-loop to view my users sorted by their first name?
Why you don`t extract them directly with SQL?
$query = "SELECT user_id, meta_value as name
FROM $wpd->usermeta
WHERE meta_key
LIKE 'first_name'
AND user_id
IN (SELECT user_id
FROM $wpdb->usermeta
WHERE meta_key='provincie'
AND ( ".$provincie_check."))
ORDER BY name";
I currently have a query that checks whether a certain word is found in the array values.
$imploded = implode("','",$company_array);
$query = "SELECT *
FROM $wpdb->usermeta
WHERE meta_key='company'
AND meta_value IN ('".$imploded."')";
The $company_array contains different values.
I want to add another WHERE clause but don't know how.
It should check on the users role:
SELECT*
FROM $wpdb->usermeta
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'subscriber'
Maybe some sort of join queries? I have no clue.
==== Sample data and expected output ====
This is my current query
$query = "SELECT *
FROM $wpdb->usermeta
WHERE meta_key='company'
AND meta_value IN ('".$imploded."')";
I want to add the following query
SELECT*
FROM $wpdb->usermeta
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'subscriber'
The first query loads a list of users that work for a certain company.
The problem is................
Crap. I just realised something while writing this.
The problem was that the administrator is also listed in the list of users. I wanted him out of the results.
The users are listed based upon their value in the company field. But if that is empty the admin isn't listed anywhere.
Your WHERE clause needs to be
WHERE (meta_key='company' AND meta_value IN ('".$imploded."'))
OR (meta_key = 'wp_capabilities' AND meta_value = 'subscriber')
try like this
$query = "SELECT *
FROM $wpdb->usermeta
WHERE (meta_key='company'
AND meta_value IN ('".$imploded."')) or (meta_key = 'wp_capabilities' and meta_value = 'subscriber')";
I think you required below. Note the () with OR for your both where clauses.
$query = "SELECT *
FROM $wpdb->usermeta
WHERE ( meta_key='company' AND meta_value IN ('".$imploded."')")
OR (meta_key = 'wp_capabilities' AND meta_value = 'subscriber');
Wordpress database, bit stuck on this one.
I'm using the following to get the ID of the current user.
$user_ID = get_current_user_id();
This returns something like this :
15
Now I try to find the matching value of $user_ID in the field show_user_list The data in this field is stored in an array.
Which looks something like this :
a:2:{i:0;s:2:"29";i:1;s:2:"15";}
This is the query i'm running (along with a set of conditions) :
global $wpdb; $result = $wpdb->get_results( "SELECT post_id FROM wp_postmeta WHERE show_user_list IN (' . implode(',', $user_ID) . ' AND post_type = 'show' AND post_status = 'publish'" );
And then I'm trying to echo the value of the matching post_id with this :
foreach ( $result as $unique ) {
echo $unique->post_id;
}
But it's not returning anything. I know I must be making a mistake while dealing with the array but I don't know where I'm going wrong?
looks like you have stored a serialized array in the show_user_list field, so it will be a hustle to search for values into using a db query.
In the model you described, you have to select all the rows from wp_postmeta that match "post_type = 'show' AND post_status = 'publish'", then manually filter results that do not have the user id in the unserialized show_user_list field.
You might try something like :
in_array($user_ID, unserialize($row->show_user_list))
Also, I noticed multiple errors in your query: string not properly concatenated with PHP code and the right parenthesis of the IN clause not closed.
Regards,
same
EDIT
Here is how I would solve your problem providing info you have given :
$user_ID = get_current_user_id();
global $wpdb;
$results = $wpdb->get_results("SELECT post_id, show_user_list FROM wp_postmeta WHERE post_type = 'show' AND post_status = 'publish'");
$user_post_ids = array();
foreach ($results as $post) {
if (in_array($user_ID, unserialize($post->show_user_list))) {
$user_post_ids[] = $post->post_id;
}
}
Hope this helps !