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:
(edit: forgot to add the parenthesis around the “in” content)
Search for mysql for IN clause