Sort LastUpdateTime not working quickbooks API PHP - php

I am getting the below error when i tried to retrieve Objects with the Simple Query in Quickbooks.
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUESTQUERY_INVALID_SORT_CRITERIA
I tried to sort using name and some other values, its working but for CreateTime and LastUpdatedTime, its not working.
Used the below function to get the Quickbooks Vendors
QuickBooks_IPP_Service_Vendor
Query used to retrieve in order:
PageNum=1&ResultsPerPage=50&Sort=LastUpdatedTime OldestToNewest
Response:
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUESTQUERY_INVALID_SORT_CRITERIA

Looking at the documentation:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/0100_calling_data_services/0030_retrieving_objects
It appears as if you're trying to sort by a field that doesn't exist.
Are you sure you didn't mean:
LastUpdatedTime
Instead of:
LastUpdateTime

My Code and Response
Code:
$ServiceName = "QuickBooks_IPP_Service_".$module;
$Service = new $ServiceName();
if ($creds['qb_flavor'] == QuickBooks_IPP_IDS::FLAVOR_ONLINE)
{
$qbmodule = "QB".$module;
$updatedtime = getLastSyncDetails($qbmodule);
$query = "";
if(!empty($updatedtime) && trim($updatedtime) != '')
{
$time = str_replace(" ", "T", $updatedtime);
$time = $time."-07:00";
$query = array('Sort' => 'LastUpdatedTime OldestToNewest');
}
}
$list = array();
$responseQuery = array();
$responseQuery = $Service->findAll($Context, $realm, $query, $page, $limit);
Response
Content-Type: application/xml
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUEST
QUERY_INVALID_SORT_CRITERIA

Related

My foreach query is not working and i am getting an error

I am getting a Warning: Invalid argument supplied for foreach() message with the code below.
The idea is that I have 2 tables, one is a stock table which has a large amount of data imported to it daily, and is linked. The other table (although not a parent table) is a list of sites, they have a common field called StockName.
The idea of this code, is that, when run, it is supposed to loop through all of the sites in the site table, get the StockName field, then use that to lookup the latest value in the stockdetails table, and then update the Site table with up to date info. Thats the theory, here is the code:
$rstmp = CustomQuery("SELECT * FROM Sites");
$datatmp = db_fetch_array($rstmp);
$SitePk = $datatmp['SitePk'];
foreach ($SitePk as $item)
{
echo $item."<BR>";
$rstmp2 = CustomQuery("SELECT * FROM ImportStockDetails where StockName='".$datatmp['StockName']."' ORDER BY `Date` DESC LIMIT 1");
$datatmp2 = db_fetch_array($rstmp2);
$latestdate = $rstmp2["LastStockDate"];
$latestcylpropane = $rstmp2["PropaneCylinders"];
$latestcylbutane = $rstmp2["ButaneCylinders"];
$latestbulkpropane = $rstmp2["BulkPropane"];
$latestbulkbutane = $rstmp2["BulkButane"];
$latesttotal = $latestcylpropane+$latestcylbutane+$latestbulkpropane+$latestbulkbutane;
$latestratio = $latesttotal/$datatmp['SiteMaxCapacity'];
global $dal;
$dal_table = $dal->Table("Sites");
$dal_table->Param["SitePk"] = $item;
$dal_table->Value["LatestPropaneCylinderStock"] = $latestcylpropane;
$dal_table->Value["LatestButaneCylinderStock"] = $latestcylbutane;
$dal_table->Value["LatestBulkPropaneStock"] = $latestbulkpropane;
$dal_table->Value["LatestBulkButaneStock"] = $latestbulkbutane;
$dal_table->Value["LatestTotalStock"] = $latesttotal;
$dal_table->Value["`Stock/LimitRatio`"] = $latestratio;
$dal_table->Value["LastStockDate"] = $latestdate;
$dal_table->Update();
}
You are getting the warning because $SitePk is not an array, it is just a value. You should try with $datatmp as db_fetch_array($rstmp); return array which is stored in $datatmp.

Property [associated_occupation] does not exist on this collection instance. - Laravel

I would like to store a database value into the variable. For some reason It's not working as expected. Below is the code in controller:
public function show(Word $word)
{
//
$curriculum = Curriculum::findOrFail($word->id);
// dd($curriculum->id);
session(['key' => $curriculum->id]);
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
$information = Information::where('curriculum_id','=', $word->id)->get();
$practical = Practical::where('curriculum_id','=',$word->id)->get();
$work = Work::where('curriculum_id','=',$word->id)->get();
$entry = Entry::where('curriculum_id','=',$word->id)->get();
$assessment = Assessment::where('curriculum_id','=',$word->id)->get();
$parts = Part::where('curriculum_id','=',$word->id)->get();
$occupurpose = Occupurpose::where('curriculum_id','=',$word->id)->get();
$occutask = Occutask::where('curriculum_id','=',$word->id)->get();
$taskdetail = Taskdetail::where('curriculum_id','=',$word->id)->get();
$purposekm = Purposekm::where('curriculum_id','=',$word->id)->get();
$guidedtopic = Guidetopic::where('curriculum_id','=',$word->id)->get();
$purposepms = Purposepm::where('curriculum_id','=',$word->id)->get();
$purposewem = Purposewem::where('curriculum_id','=',$word->id)->get();
$guidedpmstopics = Guidedpmstopic::where('curriculum_id','=',$word->id)->get();
$guidedwemstopics = Guidedwemstopic::where('curriculum_id','=',$word->id)->get();
$wordTest = new \PhpOffice\PhpWord\PhpWord();
$newSection = $wordTest->addSection();
$SectionHeading = "SECTION 1: CURRICULUM SUMMARY";
$newSection->addText($SectionHeading);
$topicHeading = "1. Occupational Information";
$newSection->addText($topicHeading);
$subTopic = "1.1 Associated Occupation";
$newSection->addText($subTopic);
$newSection->addText($knowledge->associated_occupation);
$occupationTopic = "1.2 Occupation or Specialisation Addressed by this Curriculum";
$newSection->addText($occupationTopic);
$newSection->addText($knowledge->specialisation);
$alternativeTopic = "1.3 Alternative Titles used by Industry";
$newSection->addText($alternativeTopic);
$newSection->addText($knowledge->alternative_title);
$objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordTest,'Word2007');
try {
$objectWriter->save(storage_path('TestWordFile.docx'));
} catch(Exception $e) {
}
return response()->download(storage_path('TestWordFile.docx'));
}
When I do dd of the curriculum id and the knowledge result I get correct feedback. Now I would like to store the column
associated_occupation
into the variable called newSection but I get the error mentioned on the subject. I also tried
$newSection->addText($knowledge->select('associated_occupation')); instead of $newSection->addText($knowledge->associated_occupation);
Please assist.
You are trying to access a property of a collection:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
The above will give you a collection of results that have the curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
So when you do:
$newSection->addText($knowledge->associated_occupation);
The $knowledge->associated_occupation is looking for associated_occupation on a collection of results rather than a specific Knowledge
Change your query to:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->first();
To get the first Knowledge that has it's curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
If you just need to retrieve a single row from the database table, you
may use the first method. This method will return a single StdClass
object:
Or filter the collection and pick a specific one

QuickBooks php DevKit database query only returning 100 rows

I am trying to use the DevKit to go through all existing customers in my QuickBooks Online account and update the display name for each one of them to prepend their company name with the company Id I have assigned them. Currently, there are about 1800 customers in the account.
Using the code below, I can successfully process exactly 100 of the customers each time I run the script, but it stops at this point. Is there some time or number limit to the rows return by the Service Customer query? If so, is there a way to increase it? Or is the problem something else entirely?
Quickbooks_update:
class Quickbooks_Update extends CI_Controller
{
function quickbooks_add(){
require_once 'application/QuickBooks/config.php';
$this->load->model('companyAccounts');
$success = array();
$failed = array();
$duplicate = array();
$not_exist = array();
$CustomerService = new QuickBooks_IPP_Service_Customer();
$customers = $CustomerService->query($Context, $realm, "SELECT * FROM Customer ");
foreach($customers as $customer) {
$name = $customer->getCompanyName();
$q = $this->db->select('companyAccountId');
$q = $this->db->from('companyAccounts');
$q = $this->db->where('companyName', $name);
$q = $this->db->get();
$results = $q->result();
foreach($results as $company){
$companyId = $company->companyAccountId;
}
if(sizeof($results) == 1){
$customer->setDisplayName($companyId . '-' . $name);
$resp = $CustomerService->update($Context, $realm, $customer->getId(), $customer);
if(!$resp){
array_push($failed, $name);
}else{
array_push($success, $name);
}
}
else if(sizeof($results) == 0){
array_push($not_exist, $name);
}
else{
array_push($duplicate, $name);
}
}
$data['success'] = $success;
$data['failed'] = $failed;
$data['duplicate'] = $duplicate;
$data['not_exist'] = $not_exist;
$this->load->view('quickbooks', $data);
}
}
Thank you!
QuickBooks Online by default only returns 100 rows at a time.
If you refer to the documentation:
https://developer.intuit.com/docs/0100_accounting/0300_developer_guides/querying_data
You'll find a bunch of examples of how to use STARTPOSITION and MAXRESULTS to control how many records you get back:
SELECT * FROM Invoice WHERE Status = 'Synchronized'STARTPOSITION 1 MAXRESULTS 10
SELECT * FROM Invoice WHERE Status = 'Synchronized'STARTPOSITION 11 MAXRESULTS 10
To quote the documentation:
To page through the results, specify STARTPOSITION (position of the entity in the query results) and MAXRESULTS (maximum number of entities in the result).
And:
The maximum number of entities that can be returned in a response is 1000. If the result size is not specified, the default number is 100. If a query returns many entities, fetch the entities in chunks, as described in Pagination. To determine the number of entities that a particular query returns, probe by using the COUNT keyword in the query. See Count for details.

SimpleXML to get specific data from an XML file

I am making a plugin for JomSocial that will display billing information for a logged-in user, based on an XML file. I have made good headway creating the plugin, I just cant seem to get the syntax right to create php statements so I can populate data in various places on the page. Here is the XML file:
<Inquiry>
<Billing>
<Version>4.5.1</Version>
<startTime><![CDATA[4/15/2014 11:09 PM]]></startTime>
<endTime><![CDATA[4/15/2014 11:12 PM]]></endTime>
<Date>20140415</Date>
<MemberId ID="0ESING">
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>628.32</BalanceForward>
<BalanceDue>372</BalanceDue>
<Payments>-300</Payments>
</MemberId>
<MemberId ID="F00421">
</BillingInfo>
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
<BillingSubAccount>
</BillingSubAccount>
<BalanceForward>1158.36</BalanceForward>
<BalanceDue>93.45</BalanceDue>
<Payments>-1158.36</Payments>
Here is the PHP so far:
$user =& CFactory::getRequestUser();
$cuser = CFactory::getUser();
$owner = CFactory::getUser($row->user->id);
$ptype = $cuser->getProfileType();
$billingid = $owner->getInfo('FIELD_BILLINGID');
$lastname = $owner->getInfo('FIELD_FAMILYNAME');
$uname = $cuser->username;
$memid = $cuser->id;
$name = $cuser->getDisplayName();
$isMine = COwnerHelper::isMine($cuser->id, $user->id);
$config = CFactory::getConfig();
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId->BillingInfo->Payments;
ob_start();
if( $isMine ) {
if($ptype == '2') {
if(strcasecmp($uname, $billingid) == 0) {
Then, in page to call the fields:
<?php echo "<div>Balance Due: $". $balance ." | Balance Forward: $" . $BalanceForward . " | Payment: $" . $Payments . "</div>"; ?>
This pulls in the first record of the XML file. I was trying something like this for hours:
$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId[.$uname.]->BillingInfo->Payments;
to no avail. I would like to 'pull' the child node from the XML where the MemberId ID= "yadayada" is equal to the $uname. I hope I am being clear, this is my first post on Stackoverflow!
Using the square bracket notation accesses the attribute by it's name, so you are asking for member[0ESING] which isn't right because the attribute is named ID.
You can iterate of the members to find the match like so:
foreach($xml->Billing->MemberId as $member){
if($member['ID'] == $uname){
$balance = $member->BillingInfo->BalanceDue;
$BalanceForward = $member->BillingInfo->BalanceForward;
$Payments = $member->BillingInfo->Payments;
}
}
Why are you not using simplexml_load_file() instead? It saves you the hassle in loading the file manually and putting it in a simplexml_element instead. Furthermore, I think your issues arrise because the XML file itself is invalid, it need 1 root element but instead seems to contain zero (or multiple, depends on how one would read the file).

where clause not displaying data

i am trying to display data based on wether data in a field is new. instead of showing only the data that is new it is showing all data. can someone point out my error. many thanks
<?php
include("../../js/JSON.php");
$json = new Services_JSON();
// Connect to MySQL database
mysql_connect('localhost', 'root', '');
mysql_select_db(sample);
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$new = 1;
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
}
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
}
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
// Get total count of records
$sql = "select count(*)
from act
$searchSql";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page -1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select *
from act
$searchSql
$sortSql
$limitSql";
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['slot'], $row['service'], $row['activity'], $row['department'], $row['company'], $row['address'], $row['user'], $row['item'], $row['filebox'], date('d/m/Y',strtotime($row['date'])), $row['quantity'], $row['type'], $row['new'])
);
}
echo $json->encode($data);
?>
You should debug SQL by looking at the SQL query, not at the PHP code that produces the SQL query. If you echo $sql and look at it, you'll probably see any syntax errors much more easily.
You can also copy & paste that SQL and try to execute it in the MySQL command tool, and see what happens, whether it gives the result you want, you can profile it or use EXPLAIN, etc.
You're using mysql_real_escape_string() for integers, column names, and SQL keywords (ASC, DESC). That escape function is for escaping only string literals or date literals. It's useless for escaping unquoted integers, column names, SQL keywords, or any other SQL syntax.
For integers, use (int) to typecast inputs to an integer.
For column names or SQL keywords, use a whitelist map -- see example in my presentation http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies
You're not testing for error statuses returned by any of your functions. Most functions in ext/mysql return false if some error occurs. You should check for that after every call to a mysql function, and report errors if they occur.
You're selecting a database using a constant name sample instead of a quoted string "sample". This might be intentional on your part, I'm just noting it.
Also, this is not related to your errors, but you should really upgrade to PHP 5. PHP 4 has been end-of-lifed for over two years now.
after looking at the code again and all the suggestions i think i should be using an AND clause and not WHERE. for example the code
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
this is the WHERE clause? which basically translates to:
$sql = "select *
from act
$searchSql
$sortSql
$limitSql"; <- original code
$sql = "select *
from act
WHERE company LIKE '%demo%' AND new = 1
$sortSql
$limitSql";<-updated code
am i on the right track?

Categories