PHP i need year format like 2015-16 - php

I want to store year like 2014-15 in MySQL. when i use this code means it will store -1; so plz help me out.. for Financial Year calculation.
$date=strtotime(date('Y-m-d'));
$fdate=strtotime(date('Y-03-31'));
if($date <= $fdate)
{
$facyear=(date('Y')-1)-(date('Y'));
}
else if($date > $fdate)
{
$facyear=(date('Y'))-(date('Y')+1);
}
mysql_query("INSERT INTO fyear (id, facyear) VALUES ('', '$facyear')");

You're trying to create your string using numerical operators.
Try:
$facyear=(date('Y')-1) .'-'. date('y');
and
$facyear=date('Y') .'-'. (date('y')+1);
That way it concatenates them rather than subtracting them.
That is the error you are making in your PHP code. I don't know how your fields are set up in your database, so I can't say for certain if it will still insert it correctly - but at least your string data would be correct.

Related

php - compare years with different data types

I found that ?year=2015 works on my website, the same way, ?year=2015sjkhdkfzgsfkzgsk does, when this 'year' is compared to the integer value from the database (MySQL YEAR type), somehow like this:
$year = Input::get('year');
$dbyear = Pic::find($id)->value('year');
if($year == $dbyear){
//..
}
because this seems to return true:
var_dump(2015 == '2015abcdefg34748fhhdfgxfgfg');
Is this normal or possibly a bug? How can I better compare these values? Now I am doing:
$year = substr(Input::get('year'),0,4);
You could force the argument to string data type:
$year = strval(Input::get('year'));

Compare date to today does not work

I want to display a text if the date in the database matches today's date.
$userdate = date("m/d/Y", strtotime($rr['last_login']));
$today = date("m/d/Y");
if ($userdate==$today){
echo "<test>";
}
Even if it is today's date, the records never echo out the string.
Interestingly, if I change it to
if ($userdate!=$today){
it also does not display the <test>.
My bad! I was not trying to echo out any html thing. The < brackets were just random characters. I changed it to "test" and now it works. Sorry for the < > characters causing confusion!
Since this is PHP, one would assume you're looking at the result in a browser, which will interpret the "<test>" as an HTML tag, and thus it will ignore it. Try changing the "echo" to simply echo "test<br>";
Also, if you are always dealing with a database, you could also use this:
if (substr($rr['last_login'], 0, 10) == date('Y-m-d'))
echo "test<br />\n";

PHP - Select data from where timestamp is

I have a piece of code which will select x number of days into the future and print it out.
I'm then trying to select data from those timestamps, and print out accordingly:
Below I am selecting the number of days in the future it should loop ($max) and how many rows/data there is ($data["cnt"])
$stmt=$dbh->prepare("select round((expire - unix_timestamp()) / 86400) as days, count(*) as cnt from xeon_users_rented WHERE user_by=:username group by days;");
$stmt->bindParam(":username",$userdata['username']);
$stmt->execute();
$data=$stmt->fetchAll();
$max = max(array_map(function($d){
return $d['days'];
}, $data));
$expireData = array();
I then loop through x number of days in the future and print it out: (Let's say that $x is = 10)
for($x = 0; $x <= $max; $x++){
if ($data[$x]["cnt"] > 0){
$expireData[] = $data[$x]["cnt"];
}else{
$expireData[] = 0;
}
$stamp = strtotime('+'.$x.' day', time());
$expireDays[] = date("Y/m/d", $stamp);
}
I then print out the days data and the data:
<?php echo implode("', '", $expireDays); ?>
<?php echo implode("', '", $expireData); ?>
Which gives me:
'2014/11/05', '2014/11/06', '2014/11/07', '2014/11/08', '2014/11/09', '2014/11/10', '2014/11/11', '2014/11/12', '2014/11/13', '2014/11/14', '2014/11/15'
and (where each digit represent a value for that specific date)
2,8,0,0,0,0,0,0,0,0
So far so good. The only problem here is, that the data (2,8,0,0etc.) is not correct. It should for example be:
0,0,2,0,0,0,8,0,0,0
My question is: How can I print out the data, where it matches the timestamp (xeon_users_rented.expire)?
To simplify my answer from before and to answer your question directly "How can I print out the data, where it matches the timestamp"?
You need to first put the unix timestamp of "strtotime('+'.$x.' day', time());" into an array from your original loop. Remove the expiredays[] stuff from that loop.
Then loop through that array and then use array_search for finding any matching indexes in the $data array.
if (found in $data array)
$expireDays[] = $data[array_search position]['cnt'];
else
$expireDays[] = 0;
From what I have gathered in what you are trying to establish, the sql query (for example) returns an array such as:
$data = array(
array("days"=>232975857, "cnt"=> 4),
array("days"=>232975867, "cnt"=> 10),
array("days"=>232976689, "cnt"=> 0),
array("days"=>232976688, "cnt"=> 2)
);
The max in your case is 10. However, please note that your code (below):
$max = max(array_map(function($d){
return $d['days'];
}, $data));
could return a lot of PHP E_NOTICE errors and be slow because you are working out a maximum from the unix_timestamp at that stage which is for example 232975867 (far too many loops I suspect that you need). The max should be worked out in the following way I suspect:
$max = count($data);
In my case (from my data example example) this will return something like 4 for which your for loop code will need to reference "<" not "<=". To optimise this I would actually put straight into the for loop "...; $x < count($data); ...;" unless of course you need the $max later.
Here is a big issue for me. I don't see where currently you have any correlation between the $stamp variable and the "days" column from your sql statement. Perhaps I have not seen enough information from you to fully understand or I am interpreting your question incorrectly but your sql for one will not necessarily return the same dates as the stamp variable will calculate and will not certainly return a cnt of 0 for any dates that do not exist in that table. This is why:
if ($data[$x]["cnt"] > 0){
part of the section is unnecessary and possibly incorrect.
To answer your question why do you get "2,8,0,0,0,0...." instead of the order you expected is because the sql does not return 0 cnt values as quite simply the date does not exist in it's table and your implode still returns '0's appended as you forcibly added the 0's afterwords with the line:
$expireData[] = 0;
First of all, you need to fill your data (or re-write your data to contain cnt of '0's in the correct array places). You can achieve this from the sql level with a subquery that ensures missing dates are contained and then a cnt value of 0 is enforced. I'll leave this to you to work out however another way (via PHP) is to do the following (pseudo code):
place each 'stamps' (in unix format) in array from previous loop
forloop $i through $stamps
array_search $stamps against $data['days']
if (found)
$expireDays[] = $data[array_search position]['cnt'];
else
$expireDays[] = 0;
This means that you remove the $expireDays from your first loop.
Finally, perhaps I have misunderstood and that your 'days' column shouldn't match your $stamp dates as those dates are in the future and your 'days' columns are in the past. In this case, your only option is to adjust your sql statement to forcibly include dates that are missing (between a certain date range)
Good luck.

Inserting range of dates in mysql db

I have a mysql database in which I am trying to insert consecutive dates for one year (starting 7-1-2012) and only want weekday dates inserted using php. Below is the code I have so far but get an error message: unexpected 'Y' (T_STRING) at the "values (date("Y-m-d", $i)" code on line 11. Any help is greatly appreciated.
$startdate = mktime(0,0,0,7,1,2013);
$enddate = strtotime("+1 years", $startdate);
// now we have a lower number and an upper
// number, we can loop to give dates
echo $startdate;
echo $enddate;
for($i=$startdate; $i<=$enddate; $i=strtotime("+1day",$i)) {
if ($i >=2 && $i<=6){
$insert_query = "insert into schedstats(schedDate, schedRep, reqPOD) values (date("Y-m-d", $i), 2, "All Day")";
mysql_query($insert_query) or die ("Error in query: $insert_query. ".mysql_error());
}
}
You either need to use the opposite quote style inside your other quote style, or escape your quotes, like \" or \', within a String. You should also use MySQL DATE AND TIME FUNCTIONS within MySQL.
$insert_query = "insert into schedstats(schedDate, schedRep, reqPOD) values (date("Y-m-d", $i), 2, "All Day")";
should be something like:
$insert_query = "INSERT schedstats(schedDate, schedRep, reqPOD) VALUES (DATE_FORMAT(FROM_UNIXTIME($i), '%Y-%m-%d'), 2, 'All Day')";
See http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html for more details.
Side Note:
Variables, like $i will be evaluated inside double quotes. Single Dimensional Numeric Arrays can also be evaluated in double quotes, like "What $ary[1] more info here";. If you want to put a Single Dimensional Associative Array inside double quotes, that can be done like "What {$ary['key']} more info here";. If you are putting another String inside a String, imagine that the String your putting in's quotes are being pealed off. So, if the quotes themselves need to be in the String you're putting the other String into, put them back on. If you can't get your results through any of the double quote methodologies, use concatenation, like 'What '.$ary[0]['key'].' more info here';. Since PHP will try and evaluate everything inside double quotes it may be technologically faster to use single quotes. I use double quotes all the time and it works fine, though.
mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1 1:1:1.000002');
-> '2008-01-02 01:01:01.000001'
mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998');
-> '03:00:01.999997'
Source: dev.mysql.com: function_addtime
The reason you are not getting any element inserted, is that you were checking the var $i to be between 2 and 6 (Monday and Friday?). The point is that $i is initialized to a unixtime timestamp, and that's a very high value.
First I did, was to rename $i as $tstamp, so it's more clear what it really is. Then the function isWeekDay() checks whether $tstamp is a weekday. Finally, as schedDate is a DATE field, you need to convert $tstamp from a unixtimestamp to a MySQL Date.
NOTE: According to PHP docs, weekdays ranges between 1 and 5.
<?
$startdate = mktime(0,0,0,7,1,2013);
$enddate = strtotime("+1 years", $startdate);
// now we have a lower number and an upper
// number, we can loop to give dates
echo "startdate: $startdate\n";
echo "enddate: $enddate\n";
for ($tstamp = $startdate; $tstamp <= $enddate;
$tstamp = strtotime("+1day",$tstamp)) {
if (isWeekDay($tstamp)) {
$insert_query = "insert into schedstats(schedDate, schedRep, reqPOD)
values (from_unixtime($tstamp), 2, 'All Day')";
mysql_query($insert_query)
or die ("Error in query: $insert_query. ".mysql_error());
}
}
function isWeekDay($tstamp) {
$weekday = date("w", $tstamp);
return $weekday > 0 && $weekday < 6;
}
?>

PHP - Find longest date "streak" and "slump"

I've currently got 2 dates in PHP - a 'start' date and an 'end' date. I have then created an array of dates, using a function I found called createDateRangeArray ($date_range). For simplicity, the end date will always be today's date.
I've also got a separate array that contains a bunch of dates ($valid_dates) that will always fall between the start and end dates mentioned above. On those dates, 'something' happened - in this case, a training session.
I'm trying to get my head around getting the following:
A range of dates similar to the $date_range array, populated with TRUE or FALSE based on whether or not a training session happened on that date. I'm happy for this to be an assoc array with keys named date and, say, session_found (bool).
The longest 'streak' i.e. the longest consecutive number of days that training sessions occurred.
The longest 'slump' i.e. the longest consecutive number of days that training sessions did NOT occur.
Can someone point me in the right direction for getting the above info without using a foreach on the contents of the $date_range array and then having to use another foreach for the $valid_dates array on each item in the $date_range array? That is horribly inefficient ...
Sorry if I've over-complicated things with all that info but any help would be much appreciated.
I'm currently using PHP 5.4 on Debian Wheezy, if that helps (typical LAMP stack).
Thanks
This is completely untested, but how about something like the following:
You should get the end date of the longest streak and slump, as well as how many days it took. $sessions will contain an array with the dates as the keys, and true for days with sessions, and false for days without.
Still a foreach, but I dont think you can avoid using one. Let me know if it works, I really dont have any idea how well this code will behave, but hopefully will give you a starting point?
$streak = 0;
$slump = 0;
$longeststreak = 0;
$longestslump = 0;
$longeststreakend = 0;
$longestslumpend = 0;
foreach ($date_range as $date) {
if (in_array($date, $valid_date)) {
$sessions[$date] = true;
$streak++;
// Slump broken, record the length if it beat the previous record
if ($longestslump < $slump) {
$longestslump = $slump;
$longestslumpend = $date;
}
$slump=0;
}
else {
$sessions[$date] = false;
$slump++;
// Streak broken, record the length if it beat the previous record
if ($longeststreak < $streak) {
$longeststreak = $streak;
$longeststreakend = $date;
}
$streak=0;
}
}

Categories