Sometimes the contents load and sometimes they don't - php

I have the script below and on the website http://cacrochester.com, sometimes the contents of the right sidebar load and sometimes they don't. I think it's if it's your first few times on a page, it will say no events scheduled.
I'm completely stumped on why this is happening. The data in the database is not changing.
Let me know if you need me to post anymore code.
Thanks for helping!
<?php
$dummy = 0;
$headingLength = 0;
$descriptionLength = 0;
$shortHeading = 0;
$shortDescription = 0;
$todayYear = date('Y');
$todayMonth = date('m');
$todayDay = date('d');
$events = new dates();
$noEvents = 0;
//get the number of upcoming events
$numEvents = $events->getNumberEvents();
//get the actual events
$results = $events->getRows();
//used if there are not at least 5 events to fill up the event scroller
switch($numEvents) {
case 1: $dummy = 4; break;
case 2: $dummy = 3; break;
case 3: $dummy = 2; break;
case 4: $dummy = 1; break;
}
//loops through all of the events in the table and adds them to the list
foreach($results as $result)
{
$strippedHeading = stripslashes($result['heading']);
$strippedDescription = stripslashes($result['description']);
$headingLength = strlen($strippedHeading);
$descriptionLength = strlen($strippedDescription);
$shortHeading = $strippedHeading;
$shortDescription = $strippedDescription;
$time = strftime("%l:%M %P", $result['time']);
$location = $result['location'];
$startDate = getdate($result['start_date']);
$today = getdate();
//if the events are NOT in the past...
if($startDate >= $today)
{
//if we are at the end of the array, add the class 'last' to the li
if(current($result) == end($result))
{
echo "<li class=\"last\"><h4>".$shortHeading."</h4><h6>$time</h6><h6>$location</h6></li>".PHP_EOL;
}
else
{
echo "<li><h4>".$shortHeading."</h4><h6>$time</h6><h6>$location</h6></li>".PHP_EOL;
}
$noEvents = 1;
}
//if there is not at least 5 events, it repeats the events in the list until there are 5 total
elseif($dummy > 0 && $numEvents > 0)
{
//if the events are NOT in the past...
if($startDate >= $today)
{
//if we are at the end of the array, add the class 'last' to the li
if($dummy == 0)
{
echo "<li class=\"last\"><h4>".$shortHeading."</h4> ".$shortDescription."</li>".PHP_EOL;
$dummy--;
}
else
{
echo "<li><h4>".$shortHeading."</h4> ".$shortDescription."</li>".PHP_EOL;
$dummy--;
}
//if we have 5 events, do not add anymore
if($dummy < 0)
{
break;
}
}
$noEvents = 1;
}
}
//if there are no events, display the no events message
if($noEvents == 0)
{
echo "<li class=\"last\"><h4>No Events Scheduled</h4></li>".PHP_EOL;
}
?>

When you do $startDate >= $today you are trying to compare two arrays, which isn't too good an idea. Just use plain timestamps and it should work fine:
$startDate = $result['start_date'];
$today = strtotime('today');
Also, I'm not sure if this is a typo: current($result) == end($result), but shouldn't it be $results, which is the array name?

Related

Increase variable count only if it has same value on some elements of array - PHP

I don't know either its the correct title for this question. Please, help me to edit this question if I am not adding appropriate title.
I am trying to work with hall space booking for event. There are three types of space booking:
Full - 0 (Can book by one team at same time)
Half - 1 (Can book by 2 team at same time)
Shared - 2 (Can book by 4 teams at same time)
So, I write following mention code.
<?php
$obj0 = new stdClass();
$obj0->id = '1';
$obj0->start = '2019-06-28';
$obj0->end = '2019-06-28';
$obj0->start_time = '07:00:00';
$obj0->end_time = '08:00:00';
$obj0->hall_space = '1';
$obj1 = new stdClass();
$obj1->id = '7';
$obj1->start = '2019-06-28';
$obj1->end = '2019-06-28';
$obj1->start_time = '06:00:00';
$obj1->end_time = '07:00:00';
$obj1->hall_space = '1';
$obj2 = new stdClass();
$obj2->id = '2';
$obj2->start = '2019-06-29';
$obj2->end = '2019-06-29';
$obj2->start_time = '07:00:00';
$obj2->end_time = '08:00:00';
$obj2->hall_space = '1';
$obj3 = new stdClass();
$obj3->id = '8';
$obj3->start = '2019-06-29';
$obj3->end = '2019-06-29';
$obj3->start_time = '06:00:00';
$obj3->end_time = '07:00:00';
$obj3->hall_space = '1';
$obj4 = new stdClass();
$obj4->id = '3';
$obj4->start = '2019-06-30';
$obj4->end = '2019-06-30';
$obj4->start_time = '07:00:00';
$obj4->end_time = '08:00:00';
$obj4->hall_space = '1';
$obj5 = new stdClass();
$obj5->id = '9';
$obj5->start = '2019-06-30';
$obj5->end = '2019-06-30';
$obj5->start_time = '06:00:00';
$obj5->end_time = '07:00:00';
$obj5->hall_space = '1';
$data = array($obj0, $obj1, $obj2, $obj3, $obj4, $obj5);
$hall_space = 1; //this means user is trying to book half space
if(count($data) > 0) {
$half = 0;
$shared = 0;
$error = false;
$looping_date = '';
$same_date = 0;
switch ($hall_space) {
case '0':
echo "aa";
$error = true;
break;
case '1':
foreach ($data as $dk => $dv) {
if($looping_date == $dv->start){
$same_date = $same_date + 1;
}else{
$same_date = 0;
}
if ($dv->hall_space == 0) {
echo "bb";
$error = true;
} elseif ($dv->hall_space == 1) {
$half = $half + 1;
if ($half == 2) {
echo "cc";
$error = true;
}
} elseif ($dv->hall_space == 3) {
$shared = $shared + 1;
if ($shared == 2) {
echo "dd";
$error = true;
}
}
}
break;
case '2':
foreach ($data as $dk => $dv) {
if ($dv->hall_space == 0) {
echo "ee";
$error = true;
} elseif ($dv->hall_space == 1) {
$half = $half + 1;
if ($half == 2) {
echo "ff";
$error = true;
}
} elseif ($dv->hall_space == 2) {
$shared = $shared + 1;
if ($shared == 3) {
echo "gg";
$error = true;
}
}
}
break;
}
}
if( isset($error) ){
echo "error";
}else{
echo "not error";
}
This was working fine for a singe event (i.e non-repeating). But, this is not working correctly for repeating events.
Here, in this scenario user trying to book half-space(i.e value 1) for date 2019-06-28 to 2019-06-30 from 6 am to 8am.
Above mentioned $data represents all the already booked events for that time frame, that means on every day there are are two half-spaced events (one from 6-7am and next from 7-8am) on each day. Which means this new events (half-spaced) should be allowed to book.
But, my logic is not working because, it is considering all those events as they are going to held in same date and time.That means, $half variable should be increased only if the events are on same date and time and finally should not generate error.
I tried to explain everything from myside, also you can just copy and paste the code for test. And, let me know if you need any further details.
$bookings = [
[
'period' => new DatePeriod(
new DateTime('2019-06-28 07:00:00'),
new DateInterval('PT1H'),
new DateTime('2019-06-28 08:00:00')
),
'byWho' => ['1' => 0.5, '2' => 0.5]
],
[
'period' => new DatePeriod(
new DateTime('2019-06-28 08:00:00'),
new DateInterval('PT1H'),
new DateTime('2019-06-28 09:00:00')
),
'byWho' => ['2' => 0.5]
]
];
Example data structure, between 7 and 8 on 2019-06-28 team '1' booked half the hall. Between 7 and 9 team '2' booked half the hall. All bookings should be 1 hour, if they're longer than an hour such as team two then they actually have two bookings right next to each other. If 1 hour is too long then you can change the interval if you like.
So instead of having an array of who booked when which is what you have, instead here you have an array showing a timeline, you just need to look at a specific time to see if it's booked and how full it is.
This way is better than yours because you can easily keep those dates sorted, bring this data in and out of a database into this structure with ease. Now because it's sorted you can really easily find the time you're booking for and you only need to look at the space available for that time period. But for yours you need to check every single booking to see if there is space.
If you want to check if there is space for a specific time you can use a binary search (choose your own search if you want to make this easier) to find an intersecting DatePeriod, then check values either side to find any other matching date periods. Then you simply do a check to see if in those periods there's space to fit the booking. To check for space it's as easy as summing up the values in 'byWho' + your booking size and see if it's greater than 1.

How to show event date highlight(from database) in calender php

I am using php in my project, for which I am using a JavaScript calendar. I have an event date in my database, which I want to highlight in my calendar. I have tried the following code:
PHP
$items = '';
$selq = mysql_query("SELECT * FROM ".$gettn." WHERE template_content_id = '$gettid'");
$fetselq = mysql_fetch_array($selq);
$linkId1 = $fetselq['id'];
$getevent1 = mysql_query("SELECT * FROM `template3event` WHERE tl3_id = '$linkId1'");
//$items = array();
while($fetcgetevent1 = mysql_fetch_array($getevent1)){
$items .= date('d-F', strtotime($fetcgetevent1['date'])).',';
}
$event_date = substr($items, 0, -1);
$event_dates = explode(',', $event_date);
$Event_count = substr_count($event_date , ',');
// for($z = 0; $z <= $Event_count; $z++){
// echo $event_dates[$z].'<br>';
// }
JavaScript
// fill the month table with column headings
function day_title(day_name){
document.write("<TD ALIGN=center WIDTH=35>"+day_name+"</TD>")
}
// fills the month table with numbers
function fill_table(month,month_length)
{
day=1
// begin the new month table
document.write("<DIV CLASS='calender slide1'><P>"+month+" "+year+"</P>")
document.write("<TABLE width='240'><TR>")
// column headings
day_title("S")
day_title("M")
day_title("T")
day_title("W")
day_title("T")
day_title("F")
day_title("S")
// pad cells before first day of month
document.write("</TR><TR>")
for (var i=1;i<start_day;i++){
document.write("<TD>")
}
// fill the first week of days
for (var i=start_day;i<8;i++){
document.write("<TD><a href='#'>"+day+"</a></TD>")
day++
}
document.write("<TR>")
// fill the remaining weeks
while (day <= month_length) {
for (var i=1;i<=7 && day<=month_length;i++){
var getcurrentmonth= $('#hiddenmonth').val();
var getcurrentdate=$('#hiddendate').val();
if(getcurrentmonth === month)
{
if(getcurrentdate == day )
{
document.write("<TD><a style='color:rgb(65, 255, 0)' href='#'>"+day+"</a></TD>")
}
else
{
document.write("<TD><a href='#'>"+day+"</a></TD>")
}
}
else
{
document.write("<TD><a href='#'>"+day+"<a></TD>")
}
day++
}
document.write("</TR><TR>")
// the first day of the next month
start_day=i
}
document.write("</TR></TABLE></DIV>")
}
// end hiding -->
// CAHNGE the below variable to the CURRENT YEAR
var d = new Date();
var n = d.getFullYear();
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var mm = month[d.getMonth()];
var dd=d.getDate();
today = mm+'/'+dd+'/'+n;
year=n
var leap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
var add = 0;
if(leap == true ){
add = 1;
}
//alert(add);
$('#hiddenmonth').val(mm);
$('#hiddendate').val(dd);
// first day of the week of the new year
today= new Date("January 1, "+year)
start_day = today.getDay() + 1 // starts with 0
fill_table("January",31)
fill_table("February",28+add)
fill_table("March",31)
fill_table("April",30)
fill_table("May",31)
fill_table("June",30)
fill_table("July",31)
fill_table("August",31)
fill_table("September",30)
fill_table("October",31)
fill_table("November",30)
fill_table("December",31)
I have used a query to fetch data from the database. I don't know how to proceed to the next step. I only want to use this script to achieve this, I don't want to use jQuery.

How do i get grouped random numbers in different time intervals using php

I have failed to find any problem with my code, yet it only outputs numbers from 0 to 20 without following the time restrictions i imposed. Please help me out. Below is the code:
<!DOCTYPE html>
<html>
<?php
set_time_limit(0);
class random{
var $max;
var $min;
function irregularnos($min,$max) {
$num = '';
$i = 0;
$this->min=$min;
$this->max=$max;
while($i < 25)
{
$num .= mt_rand($min,$max);
echo $num . "</br>";
$num = '';
$i++;
}
}
}
$rand1 = new random;
$rand2 = new random;
$rand3 = new random;
$rand4 = new random;
date_default_timezone_set('Europe/Berlin');
$start_time = new DateTime(); //current time
while(true){
if ($start_time->modify('+1 seconds')<= new DateTime() and $start_time->modify('+2 seconds') > new DateTime()) { $rand2->irregularnos(21,50);}
else if ($start_time->modify('+2 seconds') <= new DateTime() and $start_time- >modify('+3 seconds') > new DateTime()) { $rand3->irregularnos(51,70);}
else if ($start_time->modify('+3 seconds') <= new DateTime() and $start_time->modify('+4 seconds') > new DateTime()) {$rand4->irregularnos(71,100);}
else if (new DateTime() < $start_time->modify('+1 seconds')) {$rand1->irregularnos(0,20);}
else if(new DateTime()> $start_time->modify('+4 seconds')) { break;}
}
?>
The code is working. Probably you are expecting the code to run only once per each random number, while in reality the loop may execute very many times, say, 50 times in the first second.
For that whole second, the condition that ensues is that time is between start_time and start_time + 1 second, so the 0-20 sequence is activated.
Also, note that you are not using properly your objects - for example, the instance variables min and max are never actually used, and your call prototype would make it pointless to declare four number generators.
This code has an added pause to show all the numbers being generated:
<?php
set_time_limit(0);
class random{
var $min;
var $max;
function __construct($min, $max) {
$this->min = $min;
$this->max = $max;
}
function irregularnos($n) {
for ($i = 0; $i < $n; $i++) {
$num = mt_rand($this->min, $this->max);
echo $num . '</br>';
}
}
}
$rand1 = new random(0,20);
$rand2 = new random(21,50);
$rand3 = new random(51,70);
$rand4 = new random(71,100);
date_default_timezone_set('Europe/Berlin');
$start_time = time();
for($quit = false; !$quit;) {
// How much time has elapsed since $start_time?
switch(time() - $start_time)
{
case 0: $rand1->irregularnos(25); break;
case 1: $rand2->irregularnos(25); break;
case 2: $rand3->irregularnos(25); break;
case 3: $rand4->irregularnos(25); break;
default: $quit = true; break;
}
print "---\n";
usleep(500000);
}
?>

For loop Logic Problems with PHP

This is my new code, its almost working, but I think my while loop is wrong some where?
Same as before, gets users taken sick puts it into a var. Then get users entitlement based on years of service, then work out what they have taken and see if the user has used all the full entitlement, then to see if they have used all there half pay entitlement.
Please Help?
if($this->CURRENT_USER['User']['role_id'] > 3) { //locks out user types
//Get Holidaytypes
$types = $this->Holiday->find(
'all',
array(
'conditions' => array(
'Holiday.holidaystype_id' => 3,
'Holiday.user_id' => $id
)));
//Get starting date
$contracts = $this->Holiday->User->Contract->find(
'all',
array(
'conditions' => array(
'Contract.user_id' => $id//$data['user_id']),
'order' => array('Contract.startson' => 'ASC')
)
);
//Get How Many sick days
foreach ($types as $key => $value) {
global $SickTotal;
$typesDataEnds = strftime ("%u-%d-%Y", $types[$key]['Holiday']['endson']);
$typesDataStarts = strftime ("%u-%d-%Y", $types[$key]['Holiday']['startson']);
$SickTotal = count($typesDataEnds - $typesDataStarts);
//echo $SickTotal;
//Get Contract Start & End Dates
$start = array_shift($contracts);
$end = array_pop($contracts);
$endDate = $end['Contract']['endson'];
$startDate = $start['Contract']['startson'];
if (empty($endDate)) {
$endDate = time('now');
}
if (!empty($startDate)) {
$SortEnd = strftime("%Y", $endDate);
$SortStart = strftime("%Y", $startDate);
$YearsService = $SortEnd - $SortStart;
if ($YearsService <= 1) {
$SetFullEntitlement = 5;
$SetHalfEntitlement = 5;
//echo 'one year';
} elseif ($YearsService >= 2) {
$SetFullEntitlement = 10;
$SetHalfEntitlement = 10;
//echo 'two years';
} elseif ($YearsService >= 5) {
$SetFullEntitlement = 20;
$SetHalfEntitlement = 20;
//echo 'up to five years';
} elseif ($YearsService > 5) {
$SetFullEntitlement = 30;
$SetHalfEntitlement = 30;
//echo 'five years or more';
} else {
$SetFullEntitlement = 0;
$SetHalfEntitlement = 0;
//echo 'no sick pay';
}
} else {
$YearsService = 0;
//echo 'Sorry No Start Date For You Found!';
}
while ($SickTotal > 0) {
if ($SetFullEntitlement != 0) {
$SetFullEntitlement--;
} elseif ($SetHalfEntitlement != 0) {
$SetHalfEntitlement--;
}
}
echo 'FullPay:';
echo $SetFullEntitlement;
echo '<br/><br/>Halpay:';
echo $SetHalfEntitlement;
echo $SickTotal;
}
debug($types);
die();
//$this->render('/artists/holidayslist');
}
}
If ($startdate <= 1 year) {
If that's literally what you've typed, it's not going to work. Maybe strtotime might make some sense of it?
In any case,
For ($i = $Totalsick, $i >= $Fulldays, $i--) {
For ($i = $Totalsick, $>= $Halfdays, $i--) {
you're missing an $i in there - you're evaluating nothing against $Halfdays. You're also using $i for two seperate loops, so they're both on the same counter. switch your second loop to use a different variable.
I'm not quite sure I follow exactly what you are trying to do here but you could tidy up your code a bit and save on lines of code. I assume that $startdate is how many years ago the user started.
$sickdays= array( 0=>5, 1=>10, 2=>20, 5=>30 );
$userdays= 0;
foreach ( array_keys( $sickdays ) as $years_service )
{
if ( $years_service <= $startdate )
$userdays=$sickdays[$years_service];
}
Now $userdays should be the correct number of paid sick days and half days ( the two are always the same in your example ) for this user. A simple comparison should be sufficient to check whether they have taken less or more than their allotted number of days and half days.
I haven't tried this as I'm not working with PHP today, so I'm sure someone will shoot me down directly, but by setting your variables once and writing fewer lines you should find your code gets easier to maintain.

Show SINGLE RECORD with newest expiration date

I am using a FFDB database (flat File Database).
This script works as long as $vinc field has the same value, but I have 5 different types of $vinc values R1, R2, R3, R4, R5 - if I add new record where $vinc is not R1, a blank page appears instead.
<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
show_rec(end($result));
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
Any help?!
Thanks
Yegge, using show_rec($result[0]); it shows 1 record but instead the most recent expiration date is showing the latest expiration date:
i.e.:
1 record expire 08/01/2011
2 record expire 11/01/2011
show_rec($result[0]); is showing the record with expiration date 11/01/2011 instead of 08/01/2011
Yegge
show_rec(end($result)); worked as long as $vinc == R1 only, if adding another record where vinc is not R1 then shows a blank page, any ideas?
<?php
function getbyfunction($selectfn, $orderby = NULL, $includeindex = false)
{
if (!$this->isopen)
{
user_error("Database not open.", E_USER_ERROR);
return false;
}
// If there are no records, return
if ($this->records == 0)
return array();
if (!$this->lock_read())
return false;
// Read the index
$index = $this->read_index();
// Read each record and add it to an array
$rcount = 0;
foreach($index as $offset)
{
// Read the record
list($record, $rsize) = $this->read_record($this->data_fp, $offset);
// Add it to the result if the $selectfn OK's it
if ($selectfn($record) == true)
{
// Add the index field if required
if ($includeindex)
$record[FFDB_IFIELD] = $rcount;
$result[] = $record;
}
++$rcount;
}
$this->unlock();
// Re-order as required
if ($orderby !== NULL)
return $this->order_by($result, $orderby);
else
return $result;
}
function returnRec($item){
if($item)
return true;
}
$db = new FFDB();
if (!$db->open("foo"))
{
$schema = array(
array("key", FFDB_INT, "key"),
array("status", FFDB_STRING),
array("vinc", FFDB_STRING),
array("month", FFDB_STRING),
array("day", FFDB_INT),
array("year", FFDB_INT)
);
// Try and create it...
if (!$db->create("foo", $schema))
{
echo "Error creating database\n";
return;
}
}
$result = $db->getbyfunction("returnRec", "vinc");
foreach($result as $item) {show_rec($item);break;}
function show_rec($record){
$number = $record["key"];
$Rvinc = $record["vinc"];
$Rstatus = $record["status"];
$Rday = $record["day"];
$Rmonth = $record["month"];
$Ryear = $record["year"];
$tday = getdate();
$current_year = $tday['year'];
$current_month = $tday['month'];
if (($status == ON) && ($vinc == R1) && ($month >= $current_month) && ($year == current_year)){
echo "myrecord $vinc $status $day $month $year";
}
?>
i think you need to use break in loop, like above.
select product, expirationdate from your_table
where expirationdate > {current_date} order by expirationdate ASC limit 1
{current_date} is variable that should be passed from php or you can use mysql function instead
If I understood your code correctly, instead of
foreach($result as $item) {show_rec($item);break;}
//use
show_rec($result[0]); //only show the very first item in the result array
Edit: Then use this:
show_rec(end($result));
SOLUTION:
I just want to make sure to post the solution:
$result = $db->getall(lp_month,lp_year);
$i = 0;
foreach ($result as $row){
print_r (show_record($row));
if ($i >= 1)
break;
$i++;
}
Not a lot different from what I initially had, but print_r instead of echo did the trick:
print_r (show_record($row));
Thanks

Categories