I am trying to add an array of meta_values to a single meta_key and display them in a list like so:
Assessment One, Passed
Assesment Two, Passed
My code for updating/adding the user_meta:
$user_id = $current_user->ID;
$key = 'assessment_result';
$assessment_name = get_the_title();
$new_value = array($assessment_name, 'Passed');
$meta = get_user_meta($user_id, $key, false);
if ( ! array($meta) ) {
$meta = array();
}
$meta[] = $new_value;
update_user_meta($user_id, $key, $meta, $unique);
After completing two assessments, my array looks like this:
Array ( [0] => Array ( [0] => Array ( [0] => Array ( [0] => Assessment Two [1] => Passed ) ) [1] => Array ( [0] => Assessment One [1] => Passed ) ) ) 1
There seems to be too many arrays!
Then my query looks like this:
$user_assessment_results = get_user_meta($user_id, 'assessment_result', true);
echo '<ul>';
foreach ($user_assessment_results as $user_assessment_result) {
echo '<li>';
$output = array();
foreach ($user_assessment_result as $result_item) {
$output[] = $result_item;
}
if( count( $output ) ) echo join( ", ", $output );
echo '</li>';
}
echo '</ul>';
Which results in:
Array
Assessment One, Passed
Can you suggest where I am going wrong?
I found the problem $meta = get_user_meta($user_id, $key, false); should have been $meta = get_user_meta($user_id, $key, true);
Related
I have two meta key: us_points & agent_id
I need to sum up all the us_points value with agent ID same for each users.
Here is what I tried:
$cuser = wp_get_current_user(); $a_id = $cuser->agent_id;
global $wpdb;
$result = $wpdb->get_col("SELECT sum(meta_value) FROM $wpdb->usermeta WHERE meta_key = 'us_points' AND agent_id = $a_id" );
echo $result[0];
If I remove AND agent_id = $a_id, it shows the sum of all users in the website, but I need to show the sum of only the meta key value common/matching in agent_id
Help will me much appreciated.
Try this, It should target agent_id meta key then group records by the same agent_id value before summing.
$result = $wpdb->get_col("SELECT sum(meta_value) FROM $wpdb->usermeta WHERE meta_key = 'us_points' GROUP BY meta_value HAVING 'meta_key' = 'agent_id'" );
$users = get_users();
$agent_points = array();
foreach( $users as $user ) {
$agent_points[] = array(
'agent_id' => $user->agent_id,
'us_points' => $user->us_points,
);
}
$agent_points expected to be in the structure:
Array
(
[0] => Array
(
[agent_id] => 1
[us_points] => 30
)
[1] => Array
(
[agent_id] => 4
[us_points] => 10
)
[2] => Array
(
[agent_id] => 4
[us_points] => 30
)
[3] => Array
(
[agent_id] => 1
[us_points] => 20
)
)
Then,
$results= array();
foreach( $agent_points as $values ) {
foreach( $values as $key => $value ) {
if( 'agent_id' === $key ) {
$results[ $value ] += $values['us_points'];
}
}
}
Expected $results in agent_id => us_points pair:
Array
(
[1] => 50
[4] => 40
)
In my yii2 project I wrote query:
$Result = $query->select(['LT.Title','L.Balance', 'L.Earned'])->where(['L.EmployeeID'=>Yii::$app->user->id])->from('leave L')->leftJoin('listitems LT','LT.ListItemID = L.LeaveTypeID')->all();
and get result:
Array
(
[0] => Array
(
[Title] => sick
[Balance] => 12
[Earned] => 12
)
[1] => Array
(
[Title] => casual
[Balance] => 12
[Earned] => 12
)
)
the result is as I expected;
How can I print a single value like Title, Balance, Earned?
I tried using foreach loop but I am unable to get the result and get error Trying to get property of non-object instead.
<?php foreach ($Result as $key => $Res) {
echo "<div class='col-lg-4'>
<div class='well'>".$Res['Title']."
<p>".$Res['Earned']."</p>
<p>".$Res['Balance']."</p>
</div>
</div>";
}
?>
Doing This simply i am able to get what i wanted to .
i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400
I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);
I am trying to run two model functions from one view. The first query appears to be working fine.
The second query returns a blank array. I noticed when printing the query to the screen that the queries appear to be joining together and are not separate, like this:
JDatabaseQueryMySQL Object ( [db:protected] => JDatabaseMySQL Object ( [name] => mysql [nameQuote:protected] => ` [nullDate:protected] => 0000-00-00 00:00:00 [dbMinimum:protected] => 5.0.4 [_database:JDatabase:private] => Curling_Schedule [connection:protected] => Resource id #19 [count:protected] => 0 [cursor:protected] => Resource id #72 [debug:protected] => [limit:protected] => 0 [log:protected] => Array ( ) [offset:protected] => 0 [sql:protected] => SELECT team_name, division FROM #_autoschedTeams ORDER BY division [tablePrefix:protected] => encex [utf:protected] => 1 [errorNum:protected] => 0 [errorMsg:protected] => [hasQuoted:protected] => [quoted:protected] => Array ( ) ) [type:protected] => select [element:protected] => [select:protected] => JDatabaseQueryElement Object ( [name:protected] => SELECT [elements:protected] => Array ( [0] => sheet, id ) [glue:protected] => , ) [delete:protected] => [update:protected] => [insert:protected] => [from:protected] => JDatabaseQueryElement Object ( [name:protected] => FROM [elements:protected] => Array ( [0] => #__autoschedPlayingSheets ) [glue:protected] => , ) [join:protected] => [set:protected] => [where:protected] => [group:protected] => [having:protected] => [columns:protected] => [values:protected] => [order:protected] => JDatabaseQueryElement Object ( [name:protected] => ORDER BY [elements:protected] => Array ( [0] => sheet ) [glue:protected] => , ) [union:protected] => [autoIncrementField:protected] => )
Model:
public function getTeams()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('team_name, division');
// From the hello table
$query->from('#__autoschedTeams');
$query->order('division');
$db->setQuery((string)$query);
$teams = $db->loadResultArray();
$div = $db->loadResultArray(1);
$divs = array_unique($div);
$result = [];
foreach($divs as $key)
{
$result[$key] = [];
foreach(array_keys($div, $key) as $index)
{
array_push($result[$key], $teams[$index]);
}
}
return $result;
}
public function getSheets()
{
// Create a new query object.
$db = JFactory::getDBO();
print_r($query);
$query = $db->getQuery(true);
// Select some fields
$query->select('sheet, id');
// From the hello table
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
//print_r($query);
$db->setQuery($query);
$result = $db->loadResultArray();
return $result;
}
}
relevant code from View:
$teams_sched = $this->get('Teams');
$sheets_sched = $this->get('Sheets');
Change the name of the variable and check with it.
If you are not getting the result again, then print the query echo $query; and check with it.
public function getSheets()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('sheet, id');
$query->from('#__autoschedPlayingSheets');
$query->order('sheet');
$db->setQuery($query);
$Sheets = $db->loadResultArray();
print_r($Sheets);
return $Sheets;
}
I did the Facebook Registration Plugin like in the official Facebook tutorial and with this code there it shows the total Array on screen:
if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
echo '<pre>';
print_r($response);
echo '</pre>';
} else {
echo '$_REQUEST is empty';
}
this brings me the following array:
signed_request contents:
Array
(
[algorithm] => HMAC-SHA256
[expires] => 1324xxxx400
[issued_at] => 132446xxx80
[oauth_token] => AAADRjT73VhwBALl6Gb3EVarvyGU7xxxxxxxxxxxxxxxxxxxSAUuoZAGlydkX2pH3
[registration] => Array
(
[name] => Philipp Mail
[email] => p.mail#xxxxde
[location] => Array
(
[name] => Munich, Germany
[id] => 1.1604xxxxxx286E+14
)
[birthday] => xx/xx/19x7
)
[registration_metadata] => Array
(
[fields] => [{'name':'name'}, {'name':'email'}, {'name':'location'}, {'name':'birthday'}]
)
[user] => Array
(
[country] => de
[locale] => de_DE
)
[user_id] => 10xxxxxxx5426
)
Now I changed it for storing several data to mysql:
if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
$name_arr = explode(' ',$name,2);
$vname = $name_arr[0];
$zname = isset($name_arr[1])?$name_arr[1]:'';
$email = $response["registration"]["email"];
$ort = $response["registration"]["location"]["name"];
$anrede = $response["registration"]["gender"];
$geburtstag = $response["registration"]["birthday"];
// Connecting to database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
// Inserting into users table
$result = mysql_query("INSERT INTO REKRU_mem (mem_id, vname, zname, ort, email, userpass, chili, regdatum, geburtstag, fbuid)
VALUES
(NULL, '$vname', '$zname', '$ort', '$email', MD5('".$gesamtpass."'),'$chili', '0000-00-00 00:00:00', '$geburtstag', '$user_fbid')");
if($result){
// GOT RESULTS
}
else
{
// Error in storing
}
}
else
{
echo '$_REQUEST is empty';
}
When I look in mysql after a registration there is a new line but it saves only the actual registration time. Can anyone of U see what is my mistake?
do not use this code in a plublic Area! You can make a SQL-Injection (could also be the problem why you cannot insert).
Try this instead of the mysql_query:
$vname = mysql_real_escape_string($vname);
$zname = mysql_real_escape_string($zname);
$ort = mysql_real_escape_string($ort);
$email = mysql_real_escape_string($email);
$gesamtpass = mysql_real_escape_string($gesamtpass);
$chili = mysql_real_escape_string($chili);
$geburtstag = mysql_real_escape_string($geburtstag);
$user_fbid = mysql_real_escape_string($user_fbid);
$result = mysql_query("INSERT INTO REKRU_mem (mem_id, vname, zname, ort, email, userpass, chili, regdatum, geburtstag, fbuid)
VALUES (NULL, '".$vname."', '".$zname."', '".$ort."', '".$email."', MD5('".$gesamtpass."'),'".$chili."', '0000-00-00 00:00:00', '".$geburtstag."', '".$user_fbid."')");