What I'm trying to do is query and sum a custom field in Wordpress for the current logged in user.
I have a website for my writing company that lets writers log in and claim work that they want to do. For each assignment, there is a field called "Word Count" where I input the word count for the article that needs to be done. To calculate how much each writer is owed for an assignment, I use the word count field (with the meta key "assignment_word_count" ) and multiply it by a flat rate that each writer is paid per word.
So far the closest script I've put together that does what I want it do is an SQL script. Unfortunately, it sums ALL of the word count fields instead of just the ones that belong to the current user. If I try to add anything to the code to limit it to the current user, the total drops to zero.
<?php
$now = current_time('mysql');
$sql = "SELECT ";
$sql .= "meta_value FROM $wpdb->posts AS posts, $wpdb->postmeta AS postmeta ";
$sql .= "WHERE posts.ID = postmeta.post_id AND postmeta.meta_key = 'assignment_word_count' ";
$sql .= "AND posts.post_status = 'paid' ";
$sql .= "AND posts.post_date < '$now' ";
$sql .= "AND postmeta.meta_value != '' ";
$results = array(); $values = array();
$results = $wpdb->get_results($sql);
$totalpay = 0;
if (!empty($results)){
foreach ($results as $result) {
$totalpay += $result->meta_value;
}
}
echo 'Total Paid: $' . $totalpay * money_format('0.0040=(#10.2n', $number);
?>
There's also another script I found that is supposed to do exactly what I'm looking for, but it tells me that the implode line is an invalid argument.
<?php
//get current user
global $current_user;
get_currentuserinfo();
// build query of ids by user
$userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'assignments')); //change this
// loop to create array of ids by user
foreach ($userPosts as $post) {
setup_postdata($post);
$ids[] = get_the_ID();
}
$idList = implode(",", $ids); //tun this crap into a list
$meta_key = 'assignment_word_count';//set this to your custom field meta key
$totalpay = $wpdb->get_col($wpdb->prepare("
SELECT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo 'Total pay: $ ' . array_sum( $totalpay); ?>
http://codex.wordpress.org/Function_Reference/wp_get_current_user use this function and get currenet user id
and then
if(currentuserid=="meabox_user")
{
display the metaboxes
.........
}
You should try first to fix your query with a hard coded user id, and then, in a second time, to work on how you pass the current user.
In the query, the right field name is post_author, not author.
Related
I am trying to get the value of meta_value field from current post.
<?php
$cupost = $post->ID;
$registros = $wpdb->get_results( 'SELECT meta_value FROM auto_postmeta
WHERE post_id = $cupost AND meta_key="mg_game"');
echo $registros[0]->meta_value . "<br/>";
?>
It does not shows the echo from $registros.
But if i put directly on the query the number of the post (post_id = 7), it shows the value of meta_value.
Thy this out:
<?php
$cupost = $post->ID;//First check if this variable gets the id, i would echo the $cupost variable to check.
$registros = $wpdb->get_results( "SELECT meta_value FROM auto_postmeta WHERE post_id = ".$cupost." AND meta_key= 'mg_game' ");
echo $registros[0]->meta_value . "<br/>";
?>
You have to concatenate the Query String with the Php Variables
Ok Guys i need your Help One More Time Please if you can??
I have a list of drop down options as a set of filter criteria.
When each is selected, it adds it to a query string and appends an equals (=) to the selection, so if i select Large, the query would be where size = large.
I have one selection called impacted, but when a user selects impacted, i dont want the query to append = to, i want it to become where impacted LIKE 'click', so that it will search anywhere in the database column impacted.
If it remains at = to, it will only bring back a selection where there is only ONE impacted system that is stored against a lesson exactly = to the selection.
SELECT p.project_id
, p.project_name
, p.department
, p.size
, p.programme
, l.captured_by
, l.stage
, l.type
, l.impacted
, l.depts_inv
, l.lesson_title
, l.lesson_learned
, l.lesson_added
FROM ll_project p
JOIN ll_lessons l
ON l.project_id = p.project_id
AND l.impacted = 'Click';
This is how it currently pulls the code in but if someone has made a selection against the impacted filter i want the query not to add = before it but 'contains' or 'like' if you know what i mean.
Here is the full code.
<?php
//Set all Variables pulled from POST of previous page
$pid = $_POST['project_id'] ;
$psize = $_POST['projectSize'] ;
$pdepts = $_POST['depts'] ;
$lstage = $_POST['stage'] ;
$ltype = $_POST['type'] ;
$impacted = $_POST['impacted'] ;
//Create Column Variable to hold Values in an array linked to the database columns
$columns = array('project_id'=>'ll_project.project_id','projectSize'=>'size','depts'=>'department','stage'=>'ll_lessons.stage','type'=>'ll_lessons.type','impacted'=>'ll_lessons.impacted');
$sqlString = null;
//Check all POSTED data is pulling through - Should be 6
//echo "Total Number Of Captured Post Variables is:";
//echo count($_POST);
$number = 0;
$queryStr = "";
$preStr = array();
//For Every POSTED Value Set the Name as Key and the Value against Each
foreach ($_POST as $key => $val ) {
if (!empty($_POST[$key])){
if(!is_array($_POST[$key]))
//Escape the VALUE by surrounding it with Quotes as it is a string the value would not be picked up on the query.
$currentStr = $columns[$key]." = '".mysql_real_escape_string($val)."'";
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
//set the Query String that i want to return from the Database and set the join on the BSKYB NUMBERS on both Tables
$queryStr = "SELECT ll_project.project_id, ll_project.project_name, ll_project.department, ll_project.size, ll_project.programme, ll_lessons.captured_by, ll_lessons.stage, ll_lessons.type, ll_lessons.impacted, ll_lessons.depts_inv, ll_lessons.lesson_title, ll_lessons.lesson_learned, ll_lessons.lesson_added FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ".implode(' AND ',$preStr);
The answer is so!
if ($key == 'impacted') {
$currentStr = $columns[$key] . " LIKE '%" . mysql_real_escape_string($val) . "%'";
} else {
$currentStr = $columns[$key] . " = '" . mysql_real_escape_string($val) . "'";
}
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
Thanks for checking it out Strawberry :)
I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)
I am using the Select query as
SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'
Here I need all the records whose ordering is less than 1 of the selected record's order($rec['ordering'] = getting from other select query ) when I am trying to echo the query I am not getting complete statement but getting only this -1' AND parent = '0'
here is the whole snippet
$where = ' WHERE (id = ' . implode( ' OR id = ', $cid ) . ')';//Pranav Dave Coded
echo $selquery = "SELECT id, ordering FROM `jos_menu`".$where; //Pranav Dave Coded
$db->setQuery( $selquery );//Pranav Dave Coded
$record = $db->loadAssocList(); //Pranav Dave Coded
if ($model->orderItem($id, -1)) {
echo "<pre>";
print_r($model);
/*exit;*/
//echo $updorderup = mysql_escape_string($model->_db->_sql);//Pranav Dave Coded
foreach($record as $rec)//Pranav Dave Coded
{
echo $aboverow = "SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'";
$db->setQuery( $aboverow );
$above = $db->loadAssoc();
echo "<pre>";
print_r($above);
}//end of foreach
}//end of if
Please suggest me where I am getting wrong.....
It looks like you may need to unwrap the -1 from the quotes:
WHERE ordering='".($rec['ordering'] - 1)."' AND parent = '0'";
Why do you trying to put everything inline?
Why not to make some preparations first?
Why not to compare resulting query with sample one?
Why don't you check every step if it return proper result?
$val = $rec['ordering'] - 1;
//let's see if $cal has proper value:
echo $val."<br>";
$sql = "SELECT id, ordering FROM `jos_menu` WHERE ordering = $val AND parent = 0";
//let's see if query looks good:
echo $sql;
//let's print sampe query to compare:
echo "<br>" ;
echo "SELECT id, ordering FROM `jos_menu` WHERE ordering = 1 AND parent = 0";
As Daniel said, you need to remove the quotes around the -1. Currently its trying to minus a string, which it wouldn't be happy with at all ;)