Amazon MWS / PHP / getting all orders - php

i'm trying to get ALL orders from amazon mws. i'm aware that i can only get 100 times at a time and need to use the "nextToken2" for paging through the data.
however, what i'm not getting is how to set setCreatedAfter and setCreatedBefore for the request .. i find it very confusing that MWS expects both values to be set.
i found this code snippet:
$t1 = date("c", time()-2*24*60*60);
$t2 = date("c", time()-1*24*60*60);
$request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
$request->setSellerId(MERCHANT_ID);
$request->setMarketplaceId(marketplace_id);
$request->setCreatedAfter($t1);
$request->setCreatedBefore($t2);
it will get all orders within the past 30 days.
but how can i get ALL orders?

To get all orders via ListOrders, set your setCreatedAfter date to a date before the earliest order that was ever taken. Set the setCreatedBefore date to the current date/time. This is just simply a range of dates for which you want orders returned. You need to create a range big enough to cover all orders.
After your first call, check for a NextToken. If it exists, you have more orders, so start a loop until NextToken is empty. Once it's empty, you have all orders.
Be aware of throttling issues. You may have to slow your operation down.
Another way is to use the Reports API, which avoids throttling issues, but has extra steps to set up.

Related

How to make the final value of a countdown become new starting value?

I am working on a school project where I am keeping track of a user's tweeting frequency per week. I have working code, but at the end of each 1-week period, I need to manually adjust the new starting tweet total and the date of one week in the future.
How can I automate it so the final tweet count becomes the new starting tweet count, and one week gets added to the ending date? Am I heading in the right direction with the code below, or should I be storing these final tweet total values in a database? Thank you!
// Get current tweet total and calculate current count
$ptTotal = $ptObject->{'statuses_count'};
$ptStart = 572;
$ptCount = ($ptTotal-$ptStart);
// Set end date & convert to EST
$ptdatestr="2017-05-30 12:00:00";
$ptdate=strtotime($ptdatestr)+14400;
// Calculate time remaining
$ptdiff=$ptdate-time();
$ptdays=floor($ptdiff/86400);
$pthours=round(($ptdiff-$ptdays*86400)/3600);
// Re-set start value and add one week to countdown
if ($ptdiff <= 0) {
$ptStart = $ptTotal;
$ptdate = $ptDate + 604800;
}
I say regardless of how you are automating this code block (see Alejandro's comment), you should move away from using any approach that includes +86400 (or a factor of). Things will go BONK in the night when daylight savings is involved.
Instead, I recommend that you integrate DateTime objects. They are highly versatile and have specific features that will aid you in your specific project. This is a full list of related functions: http://php.net/manual/en/book.datetime.php
Implementing Datetime objects and functions will make your project solid and lean. Immerse yourself in the above php manual pages and the comments that follow; and continue to research on StackOverflow.
More to your specific questions: Yes, I think you are on the right path. Yes, I think I'd store the data in a database.
Good luck.

PHP Foreach Loop Query

I've been tinkering with PHP lately (self-taught, no formal training), trying to understand how to grab data from a database and display the data somewhere. So far I have learned quite a bit, but now I am stumped.
I have a list of about 200 users in my local database in a table called site_members. The table has three fields: id, name, birth_date. Via PHP, I want to display all the users on a webpage, and have something like "Birthday soon!" be mentioned right after their name. Something like this:
John Smith (Birthday soon!)
I haven't written the code to do this, because I usually write pseudocode first before actually diving into the coding part. Here's the pseudocode:
Get the current date and time and convert it to Unix timestamp
Start foreach loop and go through list of users
Query the database table, get the birthdate of a user by their id, and store it in a variable named bdate.
Convert bdate to Unix timestamp
Subtract the current date from bdate, convert it into days remaining, and store it in a variable called remaining_days.
If the user's bdate is within 15 days (remaining_days is less than 15)
Display their name, followed by (Birthday soon!)
otherwise
Just display their name only
End if
End foreach loop
Here's my problem: With the above pseudocode once translated into actual code, there would be a database query made every time in that foreach loop. Some of the tutorials I consulted mentioned I should avoid that for efficiency reasons, and it makes sense. I ran Google searches to find something similar, but that didn't do much. I do not want anyone to write any actual code for me. I just want a better solution to the querying.
Thanks in advance!
I think your concept for the pseudo code is right, and you're understanding of doing multiple database queries is also right, you just tangled the two into giving you a wrong idea.
If you construct your select statement properly (that's basically what you'd be using to access the database), you actually pull the information for everyone out of the database and store it once in an array (or some other form of object). You can then start your foreach loop using the array as your value and perform the rest of your checks that way.
$date = date("m.d.y");
$people = ** insert your commands to grab the info from the DB **
foreach($people as $person) {
// do your comparison checks and echo's etc in here
}
Does this make sense?
There can be two solutions to your problem:-
1:
Instead of making query for every user, first get the data for all the users.
Traverse the data using foreach loop php
Do the processing and display the results.
2:
Store the user date_of_birth in proper mysql date datatype
Change your mysql query to use date function to get all the users who match your date difference criteria and just display those users.
It seems you failed to read up properly on the relationship between SQL and PHP. If you actually posted code, then you could have been easily unstumped because there are many ways to do the simple task from legacy tutorials to current PDO or even MVC within in 5mins or less.
I'm not going to write the code but you need to change HOW you think in your "pseudo code".
The problem with your pseudo code is because you believe that the DB is not smart and you are doing it as if it was only for storage.
The correct pattern for PHP is the following:
1) use the Date function to retrieve current day + 15. Get month and
day only.
2) you make a SQL query that retrieve all users who's
birth_date field's month and day are GREATER THAN (or equal) to
TODAY and who are less than or equal to today + 15 (day and month
only)
3) execute the query.
4) with the returned data set (if any)
you can choose two path depending situation and design
a) you can loop it with a simple FETCH which fetch each row retrieve
and display name and extra message.
or
b) iterates through the result set and store the display message
into a variable and then finally display it once the iteration is
done.
(option b is prefered because its more flexible since you can use this technique to out into a file instead of an echo)
THIS pseudo-code ensures that you are only retrieve the correct data set with the aid of the SQL system (or storage system).
In terms of overall process, aashnisshah is absolutely correct. First, you should retrieve all the records you need from your database then loop through each row to do your data comparisons and finally close the loop.
As for finding out if their birthday is close and if you want MySQL to do the hard work, you can build your query like that in PHP:
$query = "SELECT *, DATEDIFF(DATE_FORMAT(dob, '" . date('Y') . "-%m-%d'), CURDATE()) AS days_to_dob FROM Members";
The idea is to fetch an extra column called 'days_to_dob' containing the amount of days until that person's date of birth. Note that it will be negative if that date has passed for this year. With that extra column you can easily evaluate whether their dob is within 15 days.
If you don't want any php code, then here is my pseudocode:
Get date and time -> UTC stamp and store in $time_current
Get all from site_members and store in $data
for each entry in $data, store in $record
get birth_date from $record and convert to utc stamp and store in $birthday
print name from $record
if $birthday is close to $time_current then print "Birthday soon" end if
print new line
end for
That performs only one request to your database.

Google Analytics Apiget total amount

I am trying to work with the Google analytics API. I use following code to request data:
$ga = new gapi($ga_email,$ga_password);
$ga->requestReportData($ga_profile_id,'date',array('pageviews', 'visits'), 'date', "",$start,$end,1,1000);
$results = $ga->getResults();
Which can then be iteratd with a loop for each date
After googling I can't seem to find the answer or it is possible to get the total visits, pageviews, newvisits, uniquevisits,percentnewvisits.... for a certain timespan?
If you request for example.
Dimesnion: Date
Metrics: Pageviews,visits, UniqueVists
StartDate: 20130101
endDate: 20130201
You will have a row for each date between Startdate and endDate with the values summed up for that
date.
If what you want is them summed up for all the dates then You could try a dimension like Visitor type then you will only end up with 2 rows new visits and returning visits. Summed up for the time between startdate and end date.
Unfortuantly you have to select at least one dimension so you cant just get the Metrics. Using Visitor type should work then you only have to sum up the two rows that come back. Another idea would be if your start date and end date have the same Year then you could use ga:year as your dimension. Then you will only have one row summed up with all your metrics.
Edit: found something else.
You could also try looking at totalsForAllResults it appears to be returned in the V3 of the core reporting client library.

Handling monthly occurances with PHP

I have a website where people record (or log) the distance of their runs. I want to create a leader board that will automatically reset to zero after the month is over. If I could save their total distance for that month as well, that would be ideal. Every run is tied to IDs and I have a variable that adds up the monthly distance, but obviously when they log a new run that changes. I don't know how I would make it record this month only and not freak out if they log in advance.
Any help would be appreciated.
I have tried making a monthly distance value for MySQL so each time they log, if it is that month, it will add to it. But how should I make it reset?
You're tracking the date of each run, right? Then you should be able to do something like this and avoid having to store the totals:
SELECT SUM(Runs.Miles) as MonthlyTotal
FROM Runs
where MONTH(Runs.Date) = MONTH(CURDATE()) and YEAR(Runs.Date) = YEAR(CURDATE())
(Presumably you'd also filter by or group by the UserID. Also, I suspect it may be more efficient to pre-calculate the beginning and end of the month and use BETWEEN in the where clause. Consult our friend EXPLAIN.)
If your read load is too high to make this practical, you could store the monthly total in a different table and update it with a trigger every time a run is added or updated, and via cron at the start of every month. This kind of de-normalization always makes things more complicated, so I avoid it until I have reason to believe it's necessary.

iCal backend - recurring dates

I am building a calendaring system using FullCalendar as the front end. The backend will be MySQL/PHP.
It will store a list of public appointments for users which are generated and inserted by the application. These appointments will be a single event which will start and finish on the same day. In addition users will be able to mark their unavailablity in the calendar due to personal commitments. This latter functionality requires the use of recurring events. Rather than re-invent the wheel I have been looking at using a structure based on iCal. This post was very helpful ical-field-list-for-database-schema-based-on-ical-standard in determining the database structure.
I have created the application form which allows the user to enter the necessary data in order to store a private single/recurring appointment. Upon submission of the form, the data is sent via Ajax to the server. I have found a great PHP script which generates an array of the recurring dates based on the parameters entered by the user, either in their native format or using RRULE.
I am unsure what is the best way to store/retrieve these recurring dates. The application needs to be able to render a calendar view for the user including the public and private dates. The application will also need to be able to return for example all users who may be free for a given time/date period.
Is it sufficient to store all events in the iCal format, and be able to retrieve events upon demand? The problem that I foresee is that repeating events are not easily searchable as their parameters would have to be expanded on the fly? I was considering creating a second table of every individual event (as generated ) with a reference back to the original RRULE that created it. I would look to limit the number of recurring dates that users may enter in order to prevent users from entering an event every day for the next 100 years! I think that this approach would also me to edit individual events which were originally created by a recurring rule.
Is this a good approach, or is there a better way?
Have a look at when building a calendar app, should i store dates or recurrence rules in my database?.
You should store the rrule, exrule, rdate and exdate associated with validity information (to be able to track changes over time : like if your users might want to look back in the past when they had a specific event happen and if the rrule changed between the occurence and the point of time when he/she looks back),
For events which have finite number of occurences do a pre-computation of start and end for a time window for easier queries and have a rolling window for which you have the occurences of all events in a table. When users look for occurences out of the time window (should be rare to have people looking more than one year back or more than one year in future) you compute relevant events specific for the time window the users is requesting and generate them on the fly.
How about a table along the following lines:
CREATE TABLE RecurringAppointments (
startdate DATE NOT NULL,
enddate DATE,
freq INT NOT NULL, -- contains #days between each occurrence
-- etc.
)
Then, to fetch all such appointments that occur on a given thedate:
SELECT * FROM RecurringAppointments
WHERE
thedate BETWEEN startdate AND enddate
AND DATEDIFF(thedate, startdate) % freq = 0;

Categories