Joomla 3: selecting multiple custom user fields into one html table - joomla3.0

Forgive me - pretty much a Joomla/SQL rookie and trying to navigate through some tasks I trying to help my local home owners association with.
I'm looking for a way to build my own user list containing multiple custom user fields. My current query gives me multiple records for each user because each user is linked to multiple fields in the "__fields_values" table. I need only ONE record for each user and each custom field as a seperate value in this row.
A simple group clause doesn't seem to cut it.
Nevermind the actual table html, that's just for testing right now.
Hope someone can help me see the light :)
Now I get:
username1|field1|<blank>|email
username1|field2|<blank>|email
My table should look like:
username1|field1|field2|email
My current query and output:
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__users', 'u'))
->join('INNER', $db->quoteName('#__user_usergroup_map', 'm') . ' ON (' . $db->quoteName('u.id') . ' = ' . $db->quoteName('m.user_id') . ')')
->join('INNER', $db->quoteName('#__fields_values', 'f') . ' ON (' . $db->quoteName('u.id') . ' = ' . $db->quoteName('f.item_id') . ')')
->where($db->quoteName('group_id') . ' = ' . $group_id)
->order($db->quoteName('u.username') . ' ASC')
$db->setQuery($query);
$users = $db->loadObjectList();
And then output to this table:
<table style="width:100%">
<tr style="border-bottom:1pt solid black;text-align: left;">
<th>Name</th>
<th>CustomField1</th>
<th>CustomField2</th>
<th>Email</th>
</tr>
<?php
foreach($users AS $user)
{
?>
<tr>
<td><?php;
echo $user->name;
?></td>
</td>
<td><?php;
echo $user->value;
?></td>
<td><?php;
echo $user->NEED ANOTHER VALUE HERE;
?></td>
<td><?php;
echo $user->email;
}?>
</table>

Probably You can do something like this to concatenate the result. If you are not getting the exact result you can just play with the code for what result you want. Your fields will be in the field array.
I have used CONCAT and GROUP_CONCAT. And you can have a look at it here https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php
$query = $db->getQuery(true)
->select(
array(
'*',
"CONCAT('[',GROUP_CONCAT(".$db->quoteName('f.value')."),']') field"
)
)
->from($db->quoteName('#__users', 'u'))
->leftJoin($db->quoteName('#__user_usergroup_map', 'm') . ' ON (' . $db->quoteName('u.id') . ' = ' . $db->quoteName('m.user_id'). ')')
->leftJoin($db->quoteName('#__fields_values', 'f') . ' ON (' . $db->quoteName('u.id') . ' = ' . $db->quoteName('f.item_id') . ')')
->where($db->quoteName('group_id') . ' = ' . $group_id);
$db->setQuery($query);
$users = $db->loadObjectList();
This will result in a singly array which you can do a var_dump() and check for yourself.

Related

Coinbase API getBalance ignoring ETC currency

The PHP uses the Coinbase API to get the current balance and list what currencies the account has money in. It has been used for a few weeks now, but since swapping one currency into ETC (Ethereum Classic), the balance ignores this currency. It works for all other currencies I have tried, so what is special about ETC that Coinbase is not returing anything via the API. The coinbase website portfolio does report the ETC balance correctly, so it's definitely a API issue.
<?php
include 'cfg.php'; // Contains API key
require_once ('vendor/autoload.php'); // Loads the API libraries
use Coinbase\Wallet\Client as Client;
use Coinbase\Wallet\Configuration as Configuration;
use Coinbase\Wallet\Enum\Param;
use Coinbase\Wallet\Resource\Transaction;
$configuration = Configuration::apiKey($cbase_API_Key, $cbase_API_Secret);
$client = Client::create($configuration);
$stime = $client->getTime();
echo '<h2> Server Time ' . $stime['iso'] . '</h2>';
$balance = 0.00;
$accounts = $client->getAccounts(); // Get the account(s)
echo '<table>';
foreach ( $accounts as $acct )
{
$amt = $acct->getBalance()->getAmount() ;
echo '<tr>';
echo '<td>' . $acct->getCurrency() . '</td>';
echo '<td>' . $acct->getName() . '</td>';
echo '<td>' . $acct->getBalance()->getAmount() . '</td>';
echo '<td>' . $acct->getNativeBalance()->getAmount() . '</td>';
echo '</tr>';
$balance = $balance + $acct->getNativeBalance()->getAmount();
}
echo '<table>';
echo '<h2> Total Balance: ' . $balance . '</h2>';
?>
The issue came down to pagination:
The fix therefore was to set the pagination limit to 100 (max allowed).
The default is 24, hence why the returned list was incomplete.
$accounts = $client->getAccounts(['limit' => 100]);

Wordpress admin - Where in database is it set?

I'm looking to grab admin user emails to use within a contact form. I have 2 admins that I've assigned. I'd like to grab them from the database. Where is/what is the designation point that I can use when I make the sql statment?
You can do the following
global $wpdb;
//comma separated list
$admins=$wpdb->get_var('select group_concat(`user_email`) as `admin_emails` from `' . $wpdb->prefix . 'users` as `users` inner join `' . $wpdb->prefix . 'usermeta` as `usermeta` on `usermeta`.`user_id`=`users`.`ID` where `meta_key`=\'wp_user_level\' and `meta_value` in (8,9,10);');
//array of associated arrays
$admins=$wpdb->get_results('select `user_email` from `' . $wpdb->prefix . 'users` as `users` inner join `' . $wpdb->prefix . 'usermeta` as `usermeta` on `usermeta`.`user_id`=`users`.`ID` where `meta_key`=\'wp_user_level\' and `meta_value` in (8,9,10);', ARRAY_A);
<?php $user_info = get_userdata(1);
echo 'Username: ' . $user_info->user_login . "\n";
echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";
echo 'User ID: ' . $user_info->ID . "\n";
?>
You can pass the User id herer.....
The first thing to do is to create the function. To do so, paste the following code in your functions.php file:
function getUsersByRole($role) {
$wp_user_search = new WP_User_Search($usersearch, $userspage, $role);
return $wp_user_search->get_results();
}
Once done, you can call the function this way:
$editors = getUsersByRole('Administrator');
foreach($editors as $editor){
//$editor now holds the user ID of an editor
}

how to print out all certian json data in database?

What I'm trying is I have a page which you can input 3 angel integers and submit.
After you submit the data will be saved in database using json encode
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
The above is what's saved into a row
I used
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
}
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
This prints out angel 1 : ## where ## is the angle entered and so on.
I also made a simple 2d piechart which shows the angles.
the problem I'm having is if I submit another 3 angles then my result only shows the MOST RECENT angles entered even if there are two or more in the database.
For example in my database I can see
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
{"angle1":"60","angle2":"60","angle3":"180","submit":"Submit"}
{"angle1":"30","angle2":"60","angle3":"180","submit":"Submit"}
but the result only prints 30 60 and 180 instead of printing all three.
Anyone mind giving me a hand on how I can print all three data out or at least all three sets of the angles. I believe once I figured that out I can then print out all the piecharts with all the angles instead right now only the most recent angle and the piechart are printed.
Thanks a lot people~
P.S.
I'm so so so stupid I didn't put those echo into the foreach loop but my other question is I believe I need to input my codes below into the foreach loop but there are so many tags is there a way to input all those into the foreach loop instead of doing something like echo canvas id="piechart1" blah blah blah and do it bit by bit?
<canvas id="piechart1" width="100" height="100"></canvas>
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>
<script>
var chartId = "piechart1";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $line['comp2052_angle1'].','.
$line['comp2052_angle2'].','.
$line['comp2052_angle3'];
?>];
piechart(chartId, colours, angles);
</script>
It not print 3 results, because you put them out of for scope. It only print the last $line because $line will replace every for loops.
To fixed it.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
// put the echo in for scope
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
echo '<hr/>'; // to separate each data
}
You can stored line into array then print their when you want it. for example.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
// added to stored line
$line = array();
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line[] = json_decode($option->option_value, true);
}
Then. You can mixed html and php in the pretty ways like code below.
<?php foreach($line as $i => $l): ?>
<canvas id="piechart<?php echo $i?>" width="100" height="100"></canvas>
<script>
var chartId = "piechart<?php echo $i?>";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $l['angle1'].','.
$l['angle2'].','.
$l['angle3'];
?>];
piechart(chartId, colours, angles);
</script>
<?php endforeach; ?>
Put this anywhere in html before the code above
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>

Display database array lines whilst autoincrementing id per line

I wish to display the results of a database query in my view whilst giving each row a unique ID.
My model is:
function get_load_lines($ordernumber)
{
$this->db->select('product,pricepercube,qty,linecost,linediscount,cubicvolume,bundles,treated,autospread');
$this->db->from('Customer_Order_Lines');
$this->db->where('CustomerOrderID',$ordernumber);
$q = $this->db->get();
if($q->num_rows() > 0)
{
return $q->row_array();
}
}
My controller is:
function edit_order_lines()
{
$data = array(
'ordernumber' =>$this->input->post('ordernumber'),
'customer' =>$this->input->post('customer'),
'loadlines' => $this->sales_model->get_load_lines($this->input->post('ordernumber'))
);
$this->load->view('sales/edit_order_lines',$data);
}
As mentioned I want to display each of these rows in my view.
So I use this code in my view:
<table>
<?php
$i=1;
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
$i++;
}
?>
</table>
This does not have the intended result. $i increments for each array entry, not each array line.
Any advice on the best way to display this data?
So if 3 rows the below is required:
In your model, try returning a result_array, rather than a row_array:
return $q->result_array();
If more than one result exists, result array will return all of the results, whereas row array will only return one. CodeIgniter's user guide explains the differences.
You could also make your for loop at little bit tidier, by incrementing $i like this:
$i=1;
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
}
I'm not sure I understand you question clearly, but in order to edit Customer Order Line (order details) you should also pull the ID of each Customer_Order_Lines when you query the database. (assuming your table Customer_Order_Lines has primary key filed called ID).
$this->db->select('id,product,pricepercube,q...');
Then when you loop through the results, do:
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
$i++;
}
This will give you the specific unique ID's (primary keys) of each Order Line. Then, you can updated each Order Line by referring to this ID.
Let me know if I misunderstood your question.

MultiQueries in Sphinx in cakephp

$query = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"~100';
$query2 = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"~300'
$query3 = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"/3';
$query4 = '#(name,email,biot) ' . '"' . $this->passedArgs['name'] . '"/1';
I want to execute this in one query! If I use the "|" OR operator, it takes approx 2minutes to display the results!
Is there anyway using multiquery in sphinxapi I can combine all these queries into one?
You could try
#(name,email,bio) ( "one two"~100 | "one two"~300 | "one two"/3 | "one two"/1 )
Might be a bit quicker.
If I understand (from your comment), you're looking for $this->passedArgs['name'] in the #(name,email,bio) fields, within ~100 characters OR ~300 characters OR having at least /3 words matching OR at least /1 word matching?
Why not then split it out to two different queries, the most limiting first:
$query = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"~100';
$query4 = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"/1';
perform those queries, |d together. If you get no results from it, perform the below query, also |d together.
$query2 = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"~300'
$query3 = '#(name,email,bio) ' . '"' . $this->passedArgs['name'] . '"/3';
I tried the single query using OR(|) operator, Sphinx wasn't returning accurate results. Later found out AddQuery function which helped me in getting results from multiple queries and merging into one.
I can even specify separate indexes for each query. Refer Sphinx Documentation AddQuery
$cl->AddQuery('#(name,email,bio) "one two" ~100', 'dist');
$cl->AddQuery('#(name,email,bio) "one two" ~300', 'dist');
$cl->AddQuery('#(name,email,bio) "one two" ~300', 'dist');
$cl->AddQuery('#(name,email,bio) "one two" /3', 'dist');
$cl->AddQuery('#(name,email,bio) "one two" ~/1', 'metaphone dist');
$result = $cl->RunQueries();
echo "<pre>",print_r($result),"</pre>";
I did SetIndexWeights call to prioritize multiple indexes that I have used. Refer Sphinx Document SetIndexWeights

Resources