Wordpress/PHP/MySql sort results - php

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";

Related

SELECT a value multiple time in SQL

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.

PHP/MySql search array with array

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)

PHP, SQL - getting fetch where table id = user id and count other table where row is = user id

Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);

f3 framework sql query join

I have the following tables:
tbl_users
===============
uid
username
password
gid
tbl_groups
===============
gid
name
type
I am trying to figure out how to use the sqlmapper in f3 to be able to query both tables where username equals $_POST["username"] and be able to get the group name and type as well. Is it possible to join like queries using this framework with sqlmapper?
I've been searching around and can't find any examples on that.
you can try to setup some virtual fields for this:
$mapper->group_name = 'select name from tbl_groups where tbl_groups.gid=tbl_users.gid';
$mapper->group_type = 'select type from tbl_groups where tbl_groups.gid=tbl_users.gid';
$mapper->load(array('uid = ?',123));
echo $mapper->group_name;
Here is the example with {VIEW}:
I have implemented here pagination with SQL Mapper using View view_user_list_with_referral
$dropInstantWinnerView = $this->db->exec("DROP VIEW IF EXISTS view_user_list_with_referral;");
$createInstantWinnerView = $this->db->exec("CREATE VIEW view_user_list_with_referral AS SELECT u.fb_id, fb_link, name, r.referred_by, u.created FROM users u LEFT OUTER JOIN referral r ON u.fb_id=r.joinee ");
$user = new \DB\SQL\Mapper($this->db,'view_user_list_with_referral');
$limit = 20;
$page = Pagination::findCurrentPage();
$order_condition = F3::get("PARAMS.order_condition");
$order_class= "";
if(!empty($order_condition)){
$cond = explode(":", $order_condition);
$option = array('order' => $cond[0].' '.$cond[1]);
if($cond[1]=='ASC'){
$order_condition = $cond[0].':DESC';
$order_class = ":DESC";
}else{
$order_condition = $cond[0].':ASC';
$order_class = ":ASC";
}
}else{
$option = array('order' => 'created DESC');
}
$subset = $user->paginate($page-1, $limit, null, $option);
$pages = new Pagination($subset['total'], $limit);
$pages->setTemplate("admin/pagebrowser.html");
F3::set('pagebrowser', $pages->serve());
//echo "<pre>";print_r($subset);exit;
F3::set('page', $page);
F3::set('order_condition', $order_condition);
F3::set('total_found_records', $user->count());
I hope it will save someones time :)

Check if usergroup exists

I have 2 variables which both hold comma separated lists. One is a permissions variable and the other is the usergroup list of the person wanting to access a page.
1 = user
2 = editor
3 = moderator
4 = admin
<?php
$query = mysql_query("SELECT * FROM users WHERE id='{$user['id']}'");
$user = mysql_fetch_assoc($query);
$query2 = mysql_query("SELECT * FROM menu WHERE active='1'");
$page = mysql_fetch_assoc($query2);
echo $user['usergroup']; // 1
echo $page['usergroup']; // 2,3,4
?>
I need help to find a way to compare both variables to check if they have the right usergroup to access a page
if $user['usergroup'] contains a number from $page['usergroup'] do X otherwise do Y
Thanks :)
$user = "1,3,5";
$page = "1,2,5";
//explode and trim for a case you have spaces '1, 2,3 ,4'
$u = array_map('trim', explode(",", $user));
$p = array_map('trim', explode(",", $page));
$intersect = array_intersect( $u, $p );
if ( count($intersect) )
{
//ok
print_r( $intersect );
}
else
{
//error
}
Allowed permissions:
Array
(
[0] => 1
[2] => 5
)
Try this:
$query = mysql_query("SELECT * FROM users WHERE id='{$user['id']}'");
$user = mysql_fetch_assoc($query);
$query2 = mysql_query("SELECT * FROM menu WHERE active='1'");
$page = mysql_fetch_assoc($query2);
$pageGroups = explode(',', $page['usergroup']);
if (array_search($user['usergroup'], $pageGroups) !== false) {
//TODO: User have access
}
Although I wouldn't store permissions as a commaseparated string, something like this might be what you are looking for:
$pageaccess = explode(',', $page['usergroup']);
if(in_array($user['usergroup'], $pageaccess)) {
// Has permissions. Code goes here.
}
edit: renamed $permissions to $pageaccess
While all the answers you got should work I'd like to add a comment to your approach. It's never a good idea to store comma seperated lists into your database. It offends the concept of database normalization.
Instead of storing comma seperated lists you should reconsider your database design. A possible approach could be:
users (user_id, username)
permissions(permission_id, permission)
user_permissions(up_id, permission_id, user_id)
That is much more efficient since you don't need to process the data that come from your database any further. You can just query your database and ask if the user has a certain permission.
SELECT `up_id` FROM `user_permissions` WHERE `user_id` = '{$uid}' AND `permission_id` = {5}
Taking this a step further you can assemble a little access control list:
users (user_id, username)
groups (group_id, name)
user_groups(ug_id, group_id, user_id)
permissions(permission_id, permission)
group_permissions(gp_id, group_id, permission_id)

Categories