I'm trying to evaluate and change the color of each row based on the age of the record. For some reason this statement evaluates incorrectly and just paints all rows grey. I have the following values stored in a varchar column
2015-01-12
2015-05-12
2015-05-12
So in theory the first one should be white background and the other two should be grey background. Where am I going wrong? Thanks!
while ($row = mysql_fetch_array($result))
{
$mydate = $row['Received_date'];
if($mydate < strtotime('1 month ago'))
{
echo "<tr bgcolor=\"#808080\">";
}
else
{
echo "<tr>";
}
echo "
<td style='font-size:12px;'><center>{$row['ID']}</center></td>
You are comparing a date value with a unix time value, and that doesn't work. You're halfway there, though! You're already calling strtotime() once; just do it twice and you should hopefully be fine.
$mydate = strtotime($row['Received_date']);
Related
Hi guys i got to fix some things on a website, and i got to fix this problem, there is a form in which there is a field to display the age of a person, and the age is calculated by subtracting the date the person was born (this value you have input on the field) minus the current year and but the problem is if you dont have the person's the date of birth it shows by default the current year cause the variable that holds the persons date of birth is = 0 cause nothing was inserted so, it shows on the page 2014 years old, so what i want it if nothing is displayed then dont display that field at all, and else{} solution is needed so any ideas how to solve it here is the code.
if (strcmp ( $title , "Año de nacimiento" ) ==-1)
{
if($edad!=1)
{
$fecha = date("Y");
$edad=$fecha-$c;
echo "<div class='uk-grid' data-uk-grid-margin='' >";
echo "<div class='uk-width-medium-7-10'><b>";
echo JText::_('ADSMANAGER_CAMPO_EDAD');
echo "</b></div>";
echo "<div class='uk-width-medium-3-10'>$edad años";
echo "</div></div>";
$edad=1;
}
}
By the way "Año de nacimiento" is the year of birth, $edad is the age gotten by the subtracting the year of birth - current year (2014) of course i have to put and else {} any ideas how to solve this riddle?
Try:
$edad = $fecha - ($c ? $c : 2000);
That 2000 should be a reasonable default - in this case, it would default their age to 14 years, so... try 1990 perhaps. Whatever works best for your situation.
In newer versions of PHP, you can do:
$edad = $fecha - ($c ?: 2000);
Well guys this worked for me guys, in order to give the order of not displaying the age field in case is not given by the admnistrator, what i did is this:
$fecha = date("Y");
$edad = $fecha - $c;
if($edad!= $fecha){same logic as before}
As you can see i put the age calculation before the if{} so if the age calculation is not equal to the current date, then display the field with the age, else would mean that the age is the same (current date is the default age when date of birth is not given) as the current date so dont display anything or since it was not given dont display it. Thanx anyways guys i am proud to have solved this by my own!
I'm working on a time management system and am currently stuck. I'm trying to use PHP to calculate the number of hours/minutes between two columns (from and to). These are both set as 'time' type so MySQL recognises it as a time datatype.
I've tried the following in PHP:
$from= isset($_GET['from']) ? '%'.$_GET['from'].'%' : '';
$to = isset($_GET['to']) ? '%'.$_GET['to'].'%' : '';
$diff = $to - $from;
echo "<table border='1'>
echo "<tr>";
echo "<td>" . $row[$diff] . "</td>";
echo "</tr>";
echo "</table>";
Say for example 'to' is set at 15:00:00 and from is set at 09:00:00, then the time difference for that row should be 6 hours and this should be displayed for that row.
The variable $difference is supposed to echo the difference in hours/minutes but it just displays the id assigned to that row instead. I'm trying to echo the number of minutes for each row in the table not just one.
I've seen the timediff function but don't know if that will do the trick.
I don't see your logic with the % and the $_GET vars, and $row suddenly appears out of nowhere.
You should convert the inputted times to php DateTime classes.
An example shows calculating diffs: http://nl1.php.net/manual/en/class.datetime.php#108970
Create your DateTime for example like this:
$dateFrom = new DateTime("2014-02-24 ".$_GET['from']);
$dateTo = new DateTime("2014-02-24 ".$_GET['to']);
$diff = $dateFrom->diff($dateTo);
print_r($diff) ;
The day you use is not really important if you only need the difference in time.
this is my events script that pulls out appointments for the next 7 days, it appears to work ok, but only under one condition........The dates and times are held in the mysql db in datetime format so 2013-12-23 08:30:00 . My script prints out each day and finds appointments for that day for customers that are dropping off or picking up things. The mysql looks through the db and matches the customers with the dropping off or picking up fields to the date being printed and adds them in the div below the date.
The problem I am having is that if the time is set to anything other than 00:00:00 it doesn't pickup that customer for that day. How do I get the comparison to ignore the time and only use the date ?.
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//
What you are doing right now is comparing date/time values to just date values. This comparison would fail if the time part is anything other than midnight.
You can fix the comparison by using the DATE() MySql function to compare apples with apples:
WHERE DATE(datedroppingoff) = '$theday' OR DATE(datepickingup) = '$theday'
There are other ways to do the same, for example
WHERE DATEDIFF(datedroppingoff, '$theday') = 0 OR ...
If you had a $nextday value at hand you could also do
WHERE (datedroppingoff >= '$theday' AND datedroppingoff < '$nextday') OR ...
You are storing a specific time and day in mySQL, but only search for a date in your SQL query. As mySQL does not understand the difference between you wanting to search for a complete day or a specific point in time, mySQL assumes you are looking for the day at time 0:00:00.
You have a few options, you could search for a time period (pseudo code, check the borders yourself):
WHERE datedroppingoff > '$theday' AND datedroppingoff < '$theday'+1
another option is to store the date and time in separate db fields. That way you can keep your SQL queries simpler.
Good luck.
This question already has an answer here:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in php [duplicate]
(1 answer)
Closed 9 years ago.
Hi I have the following code which works fine on one server but I get the following error on a free server I have used
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/a9645958/public_html/tteeth/staffslot.php on line 75
my code is as follows:
// Starting of top line showing name of the day's slots
echo "<form method='post' name='time' action='timeinsert.php'>
<table align='center' width='380' border='1'>
<tr>
<th>Select</th>
<th>Appointment Times</th>
</tr>";
// Starting of the slots
for($i=0;$i<=31;$i++){ // this shows 32 x 15 minute slots from 9:00am - 17:00pm
$shr=9+floor($i/4); //calculates the start hour of a slot
$smin=($i%4)*15; //calculates the start minutes of a slot
$time=mktime($shr,$smin,00,0,0,0); //creates full php time from hours and minutes above
$displayTime2=date("H:i:s",$time); // creates correct time format for MySQL database hrs, mins, seconds
$pagetime = date("H:i a", strtotime($displayTime2)); //converts the time to just hours and minutes
$timenow = date('H:i'); // get's the current time
$chosendate = date(mktime(0,0,0,$month,$day,$year)); // converts the date picked to php time (seconds since 01 01 1971)
$todayDate = date(mktime()); // converts today's date to php time so it can be compared with the chosen date
while ($myrow = mysql_fetch_row($result)) {
printf("<tr><td>%s</td><td>%s</td></tr>\n",
$myrow[0]);
}
$result=mysql_query("SELECT * FROM appointment where Appointment_Time='$displayTime2' AND Appointment_Date='$insertdate' AND Practice_ID='$practice'");
$myrow = mysql_fetch_row($result);
if($pagetime<$timenow AND $chosendate<$todayDate) //if the display time is less than the time now, and the date is less than todays date
{ //do not display a row
}
elseif($myrow)// if the values in the database match the row slot time
{
echo "<td></td><td align='center'>$pagetime</td>";//just display the slot as a time
}
else
{
echo "<td align='center'><input type='checkbox' name='$displayTime2' onclick='KeepCount()'></td>
<td align='center'>$pagetime</td>";
}
echo "</td></tr>";
}
echo "</table><br>
<input type='submit' value='Submit'>
</form>";
I'm pretty cofident that the problem is with the print f function because it asks to print the table header for however many values there are in $myrow, but it hasn't got the valuue of it yet...but if I move it to after the select statement, it messes up the rest of my code (it doesnt compare the time with whats in the db, and there are problems inserting into the db on the following page)
Here you are trying fetch result whicht not exist in that moment.
while ($myrow = mysql_fetch_row($result)) {
printf("<tr><td>%s</td><td>%s</td></tr>\n",
$myrow[0]);
}
You should put that while loop after this
$result=mysql_query("SELECT * FROM appointment where Appointment_Time='$displayTime2' AND Appointment_Date='$insertdate' AND Practice_ID='$practice'");
I want to write an IF statement based on two dates.
I have a MySQL database (of which I have no control over) for tests and exams taken.
One of the fields is labelled ClientTime and outputs the date and time the test was taken. When queried the typical output would read as such Thu Aug 25 16:47:05 GMT+0100 2011
The following all happens in a while loop
I’ve managed to convert this MySQL date using strtotime() to a d/m/Y format so the above would read 25/08/2011 and I can display a table with all the correct dates.
I also have a php form that asks for the number of days that this test will expire after and this gets stored in a variable $IMonths (from the $_POST['IMonths'] passed from the form page) - the php code will be changed to Months once I have it working but I am using days for the purpose of testing – hence the variable passed being called $IMonths.
I have also created a $today = date("d/m/Y"); variable
I can successfully create a new date using the following command $Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days")); and can display all results with both the test date and the expiry date.
I then want to include an if-statement within my while-statement that says is ($Expiry>$today) but it’s not accurate – there are no errors and changing the number of days changes the results.
My test database has 5 exams in with the following dates.
Taken 17/08/2011
Taken 17/08/2011
Taken 22/08/2011
Taken 22/08/2011
Taken 24/08/2011
If I set the expiry days to 1, I get all results back as expected:
If I set it to 10 days I get two results
Taken 17/08/2011
Taken 17/08/2011
I don’t get any of the others even though their date will be less than today's date (07/09/2011 (as I write this)) but they do expire in the month of September.
If I set the expiry days to 15, I get one result that is one day in the future!
Taken 17/08/2011
I hope that makes sense. My code is as follows:
<?php
// Make The MySQL Server Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
// Make The MySQL Database Connection
mysql_select_db("questions") or die(mysql_error());
$IQuizName = $_POST['IQuizName'];
$IMonths = $_POST['IMonths'];
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName='$IQuizName'
AND PassFail='Pass'") or die (mysql_error());
$today = date("d/m/Y");
echo "<table border='1'>";
echo "<tr> <th align='left'>Candidate Name </th> <th align='left'>Pass / Fail</th> <th align='left'>Date last Taken</th> <th align='left'>Expires</th> <th align='left'>Today</th> </tr>";
while($row = mysql_fetch_array($result)){
//START of expiry calculation
$Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days"));
if($Expiry>$today){
echo "<tr><td>";
echo $row['Candidate'];
echo "</td><td>";
echo $row['PassFail'];
echo "</td><td>";
//Date Conversion
echo date('d/m/Y', strtotime($row['ClientTime']));
echo "</td><td>";
echo $Expiry;
echo "</td><td>";
echo $today;
echo "</td><tr>";
};
}
echo "</table>";
echo "<P>";
?>
Your issue is due to datatypes in PHP. When you call the date() function in PHP, you are actually formatting dates into strings. So when you do $Expiry = date(blahblah), $expiry is now a string. So your if statement is if (somestring > someotherstring). Normally you would not think to compare one block of text to see if it is greater than another block of text.
http://www.php.net/manual/en/function.date.php
One way to get around this would be the strtotime function. This returns integers that are based on UNIX timestamp for the date representation.
http://www.php.net/manual/en/function.strtotime.php
If you convert your string dates to strtotime, your if statement is now comparing if one number is greater than another. This should solve your problem :)
First: fix that SQL-injection hole.
I suggest querying the expiry dates in SQL, it will be much easier.
Here's example code
//escape those user variables !!
$IQuizName = mysql_real_escape_string($_POST['IQuizName']);
$IMonths = mysql_real_escape_string($_POST['IMonths']);
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName= '$IQuizName'
AND PassFail= 'Pass'
AND ClientTime < NOW() ");
//don't use (or die(error)) in production code, (for now I'll let it slide).
if (!$result) then { die (mysql_error()); }
while ($row = mysql_fetch_row($result))
{
echo "the table"
}
For accurate comparing dates you should convert the dates with the strtotime function again.
In PHP there is no standard date data type. What you have is strings, and when you compare them, they get compared as strings, not as dates, thats why you get results you dont expect. How it normally is done in PHP is to format your date string by ordering from most significant bit to least bit, like
YYYY-MM-DD HH:MM:SS
If you do that, string comparison will work as expected. You can format your dates easily using:
$string = date('Y-m-d H:i:s', $year, $month, $day, $hour, $minute, $second);