Calculate age from datebirth sql field? - php

This is the query I am using and it is in page 1 not inside the function.
<?php
$sql2= mysql_query("SELECT *
FROM catego WHERE category_id = '$idc'");
$categoryCount = mysql_num_rows($sql2);
if ($categoryCount>0 )
{
$row2 = mysql_fetch_array($sql2);
$id = $row2["category_id"];
$birthdate = $row2["birthdate"];
$address = $row2["address"];
}
?>

SELECT YEAR(SUBDATE(NOW(), INTERVAL DATE_FORMAT("1975,09,02", "%Y-%m") YEAR_MONTH)) fs_age;

A simple php function could be something like the following:
function birth_date ($birth_date){
list($y,$m,$d) = explode(",",$birth_date);
$y_diff = date("Y") - $y;
$m_diff = date("m") - $m;
$d_diff = date("d") - $d;
if ($m_diff < 0 || $d_diff < 0) { $y_diff--; }
return $y_diff;
}
i.e split on your commas, work out the differences, adjust for which side of their birthdate the day/month is, if so reduce the year by one, then just return the year.
Then in your page you can put:
<li><span class="label">Age:</spa><?php$age = getage($birthdate); echo $age;?> </li>
EDIT:
<?php
function birth_date($birth_date){
list($y,$m,$d) = explode(",",$birth_date);
$y_diff = date("Y") - $y;
$m_diff = date("m") - $m;
$d_diff = date("d") - $d;
if ($m_diff < 0 || $d_diff < 0) { $y_diff--; }
return $y_diff;
}
$sql2= mysql_query("SELECT * FROM catego WHERE category_id = '$idc'");
$categoryCount = mysql_num_rows($sql2);
if ($categoryCount>0 )
{
$row2 = mysql_fetch_array($sql2);
$id = $row2["category_id"];
$birthdate = $row2["birthdate"];
$address = $row2["address"];
$age = birth_date($birthdate);
}
?>

In PHP, there are a few ways to do this. Here are some good resources:
http://snippets.dzone.com/posts/show/1310
http://www.dreamincode.net/forums/topic/19953-calculating-age-tutorial/

Like this, in your language of choice:
function getAge(dateOfBirth)
{
DateTime now = DateTime.Today;
int years = now.Year - dateOfBirth.Year;
// subtract another year if we're before the birth day in the current year
if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day))
--years;
return years;
}

Related

PHP For Loop, Compare Incrementing Value to Incrementing Array

Short question: I am trying to see if a variable ($y) is between multiple array values from a database ($ending[0] && $starting[0], $ending[1] && $starting[1], etc...). "If" $y is between any of those, echo "statement".
I'm using a for loop to increment a drop down in 30 minute intervals from 9am - 7pm.
If any of those times = a time saved within my database, it echoes "not available" instead.
Now I need to see "if" the dropdown time is "between" the start and end times in the database and make those "not available" as well.
Everything works if I manually identify which array keys to compare...but my question is: can I check the drop down value against all of the values in the arrays?
Example:
Start Dropdown: 09:00am 09:30am 10:00am etc up until 07:30pm. End Dropdown: 09:30am 10:00am 10:30am etc. up until 08:00pm. If there is a start and end time of 09:00am(start) 10:00am(end) saved in the database for an appointment, the dropdown will show "Not available" for the corresponding starting and end times, so a user cannot double book an appointment. What I am asking about, is how to identify all of the "in between" values...09:30am for example, cannot be a start or an end time, if the 09:00am-10:00am slot is already booked.
$sql_slots = "SELECT * FROM XXXXX WHERE date = '$query_date' ORDER BY XXXXX ASC";
$result_slots = mysqli_query($connection, $sql_slots);
$open = strtotime("9:00am");
$close = strtotime("9:30am");
$starting = array();
$ending = array();
while($row_result_slots = mysqli_fetch_assoc($result_slots)){
$starting[] = $row_result_slots['start_time'];
$ending[] = $row_result_slots['end_time'];
}
echo'
<select name="start_time">';
for($b = 0; $b <= 20; $b++){
$y = strtotime(($b*30) . " Minutes", $open);
$the_time = date("h:ia", $y);
// Here, instead of only comparing the first values in the array, I need to match it up against $ending[1] & $starting[1], $ending[2] & $starting[2], etc...
if(in_array($the_time, $starting) || ($y <= strtotime($ending[0]) && $y >= strtotime($starting[0]))){
echo "<option>Not Available<br></option>";
} else {
echo "<option>" . $the_time . "<br></option>";
}
}
echo'</select>';
How about that?
$sql_slots = "SELECT * FROM XXXXX WHERE date = '$query_date' ORDER BY XXXXX ASC";
$result_slots = mysqli_query($connection, $sql_slots);
$open = strtotime("9:00am");
$close = strtotime("9:30am");
$reserved = array();
while($row_result_slots = mysqli_fetch_assoc($result_slots)){
$start = $row_result_slots['start_time'];
while ($start <= $row_result_slots['end_time']) {
$reserved[$start] = true;
$start = date("Y/m/d h:i:s", strtotime($start . "+30 minutes"));
}
}
echo '<select name="start_time">';
for($b = 0; $b <= 20; $b++){
$y = strtotime(($b*30) . " Minutes", $open);
$the_time = date("h:ia", $y);
if(isset($reserved[$the_time]){
echo "<option>Not Available<br></option>";
} else {
echo "<option>" . $the_time . "<br></option>";
}
}
echo'</select>';
Below is what I came up with. This uses a do while loop and creates a reserved array that will fill all time between what is given in the appointment.
I updated the data to use my own array but updated your mysqli work with what should be correct. If not I left in my testing code for you to view if needed. I also used the disabled attribute on an option over outputting some text.
<?php
$sql_slots = "SELECT * FROM XXXXX WHERE date = '$query_date' ORDER BY XXXXX ASC";
$result_slots = mysqli_query($connection, $sql_slots);
$open = strtotime("9:00am");
$close = strtotime("7:00pm");
$space = 900; //15min * 60 seconds space between?
//This seems more normal for people to see.
//Simulate these appoinments
/*
$query_results = array(
array(
"start_time" => "9:00am",
"end_time" => "9:30am"
),
array(
"start_time" => "10:30am",
"end_time" => "11:30am"
),
array(
"start_time" => "11:45am",
"end_time" => "12:30pm"
)
);
*/
$reserved = array();
while($row_result_slots = mysqli_fetch_assoc($result_slots)){
//**NOTE**: Make sure these are times or use strtotime()
$next_slot = $reserved[] = strtotime($row_result_slots['start_time']);
$end_time = strtotime($row_result_slots['end_time']);
while($next_slot < $end_time){
$next_slot += $space;
$reserved[] = $next_slot;
}
}
/*
foreach($query_results as $appoinment) {
$next_slot = $reserved[] = strtotime($appoinment['start_time']);
$end_time = strtotime($appoinment['end_time']);
while($next_slot < $end_time){
$next_slot += $space;
$reserved[] = $next_slot;
}
}
*/
echo'<select name="start_time">';
$current = $open;
do {
$disabled = in_array($current, $reserved) ? 'disabled' : '';
echo '<option ' . $disabled . '>' . date("h:ia", $current) . '</option>';
$current += $space;
} while($current <= $close);
echo'</select>';

How to convert month name to month number

i want to convert month name to month number. By using this code, it is only show a result for december, the other month didnt work. But it is work if i change the year. For example, i choose November and 2015, the result is December and 2015. and if i choose November and 2014, the result is December and 2014.
The value in the database is 2015-09-28. i think there is a mistake on how i convert month name to month number. Can someone help me to fix my code.
This is my code :
VIEW
<?php echo form_open("announcement/announcement_result");?>
<?php echo form_dropdown('m', $m, set_value('m'), 'id="m"'); ?>
<?php echo form_dropdown('q', $q, set_value('q'), 'id="q"'); ?>
<?php echo form_submit('search', 'SEARCH', 'class="button expand"'); ?>
<?php echo form_close(); ?>
CONTROLLER
function announcement_list()
{
$data['q'] = array(
'' => ' Select Year',);
for ($i = 0; $i < 10; $i++)
{
$date = date('Y') - $i;
$data['q'][$date] = $date;
}
$m = '';
$data['m'] = $m;
$data['m'] = array(
'' => 'Select Month',
);
for ($m = 1; $m <= 12; $m++) {
$month = date("F", mktime(0, 0, 0, $m));
$data['m'][$month] = $month;
}
if ($m='December')
{
$m='12';
}
else if($m='November')
{
$m='11';
}
else if ($m='October')
{
$m='10';
}
else if ($m='September')
{
$m='9';
}
else if ($m='August')
{
$m='8';
}
else if ($m='July')
{
$m='7';
}
else if ($m='June')
{
$m='6';
}
else if ($m='May')
{
$m='5';
}
else if ($m='April')
{
$m='4';
}
else if ($m='March')
{
$m='3';
}
else if ($m='February')
{
$m='2';
}
else if ($m='January')
{
$m='1';
}
$data['results'] = $this->news_model->get_announcement_list($config['per_page'], $page);
}
MODEL
function get_results($m, $q, $limit=6, $offset=0)
{
$sql = "SELECT *
FROM ArkibBerita
WHERE code='PENGUMUMAN' AND Enable = 'Y' AND Lang ='EN' AND YEAR(BeritaDate)='{$q}' AND MONTH(BeritaDate)='{$m}'
ORDER BY position ASC
OFFSET {$offset} ROWS
FETCH NEXT {$limit} ROWS ONlY";
$query = $this->db->query($sql);
return $query->result();
}
What about:
echo date('m', strtotime('january'));
Output:
01
If you don't want the leading zero use n or see the manual for other usages; http://php.net/manual/en/function.date.php.
In your code you aren't comparing the date, you are setting it.
if ($m='December')
Should be
if ($m=='December')
One equals sets. Two equals compares. Three equals compares and requires the same variable type. http://php.net/manual/en/language.operators.comparison.php
So on every iteration your $m is going to be 12 because the $m always sets to the string and that is the first condition it hits. If you inverted your order it would be set to 1.
You also should look into using prepared statements for your SQL queries. http://php.net/manual/en/security.database.sql-injection.php

Change date from database into an array

I am wondering how to the change date from this
Db -> holiday -> holidayDate (type date) = 2015-01-01, 2015-01-03, 2015-02-19, 2015-03-21, 2015-04-03, 2015-05-01, 2015-05-14, 2015-05-16, 2015-06-02, 2015-07-17, 2015-07-18, 2015-08-17, 2015-09-24, 2015-10-14, 2015-12-25
Here is the code
$sql = "select * from holiday order by holidayDate ";
//echo $sql;
$ambil_data = mysql_query($sql);
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2 = $data['holidayDate'];
}
else
{
echo mysql_error();
}
function selisihHari($tglAwal, $tglAkhir)
{
$tglLibur = array("'".$tglLibur2."'"); <= i just want to get this array from db
$pecah1 = explode("-", $tglAwal);
$date1 = $pecah1[2];
$month1 = $pecah1[1];
$year1 = $pecah1[0];
$pecah2 = explode("-", $tglAkhir);
$date2 = $pecah2[2];
$month2 = $pecah2[1];
$year2 = $pecah2[0];
$jd1 = GregorianToJD($month1, $date1, $year1);
$jd2 = GregorianToJD($month2, $date2, $year2);
$selisih = ($jd2 - $jd1);
$libur1 = 0;
$libur2 = 0;
$libur3 = 0;
for($i=1; $i<=$selisih; $i++)
{
$tanggal = mktime(0, 0, 0, $month1, $date1+$i, $year1);
$tglstr = date("Y-m-d", $tanggal);
if (in_array($tglstr, $tglLibur))
{
$libur1++;
}
if ((date("N", $tanggal) == 7))
{
$libur2++;
}
if ((date("N", $tanggal) == 6))
{
$libur3++;
}
}
return $selisih-$libur1-$libur2-$libur3;
}
into this
$tglLibur = array("2015-01-01","2015-01-03","2015-02-19",
"2015-03-21","2015-04-03","2015-05-01","2015-05-14","2015-05-16",
"2015-06-02","2015-07-17","2015-07-18","2015-08-17","2015-09-24",
"2015-10-14","2015-12-25");
First of all your function selisihHari doesn't have access to the variable tglLibur2 you're using inside it. So I'm thinking you didn't post your full code here. But what you're looking for can be done with the following code:
$tglLibur = array()
foreach($tglLibur2 as $date){
$tglLibur[] = $date;
}
But what you're doing in your fetch code doesn't make sense. You keep overwriting the same variable. To change that do the following:
$tglLibur2 = array();
if ($data = mysql_fetch_array($ambil_data))
{
$tglLibur2[] = $data['holidayDate'];
}
This should give you the array you're looking for. That way you can get rid of your function all together.
Assuming that you aren't looping through each row and that $data['holidayDate'] is a string of dates, comma delimited, just change:
$tglLibur2 = $data['holidayDate'];
to
$tglLibur[] = explode(', ', $data['holidayDate']);

How do I populate an associative array in PHP one line at a time?

I have this array:
$crops[] = array(
'Type' => $type_name,
'Method' => $method_name,
'Crop' => $crop_name,
'SowDirect' => $direct_sow_date,
'SowTransplant' => $transplant_sow_date,
'Transplant' => $transplant_date,
'BeginHarvest' => $begin_harvest_date,
'EndHarvest' => $end_harvest_date
);
What I want is to add the key/value pairs one by one within some logic code:
$crops[] = array();
if($var1 == something) {
$crops['Type'] = $value1;
}
if($var2 == something) {
$crops['Method'] = $value2;
}else{
$crops['Crop'] = $value3;
}
Using the first way, I get this, which is what I want:
http://gardencalc.drivingpeace.com/grid_data.php
Using the second way, I get this, which is NOT what I want:
http://gardencalc.drivingpeace.com/grid_data1.php
How do I make example 2 work the same as example 1?
Update 4/18/14
The answer below did the trick. The main problem I was having (and the one I hoped your suggestion would fix) is that I'm manipulating a bunch of dates within my logic decisions, and I'm using date_add() & date_sub().
If I just print the dates within the code, it works fine and I get the changes I want.
However, if I manipulate dates, add them to the array as in your method, then print the array via JSON, none of the dates are changing.
Here's your modified array code where the dates still aren't changing:
<?php
$loc_id = 174;
$prob_id = 10;
#Include the connect.php file
include('connect.php');
#Connect to the database
//connection String
$connect = mysql_connect($hostname, $username, $password)
or die('Could not connect: ' . mysql_error());
//select database
mysql_select_db($database, $connect);
//Select The database
$bool = mysql_select_db($database, $connect);
if ($bool === False){
print "can't find $database";
}
$tempSQL = "SELECT * FROM prob_28 WHERE prob_id=$loc_id";
$temp = mysql_query($tempSQL) or die(mysql_error());
while($row = mysql_fetch_array( $temp )) {
$prob1_90 = $row['prob1_90'];
$prob1_50 = $row['prob1_50'];
$prob1_10 = $row['prob1_10'];
$prob2_10 = $row['prob2_10'];
$prob2_50 = $row['prob2_50'];
$prob2_90 = $row['prob2_90'];
}
//build the dates
if ($prob_id == "10"){
$first_frost_date = date_create(date("Y").'-'.substr($prob1_10,0,2).'-'.substr($prob1_10,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_10,0,2).'-'.substr($prob2_10,2,2));
}elseif ($prob_id == "50"){
$first_frost_date = date_create(date("Y").'-'.substr($prob1_50,0,2).'-'.substr($prob1_50,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_50,0,2).'-'.substr($prob2_50,2,2));
}else{
$first_frost_date = date_create(date("Y").'-'.substr($prob1_90,0,2).'-'.substr($prob1_90,2,2));
$last_frost_date = date_create(date("Y").'-'.substr($prob2_90,0,2).'-'.substr($prob2_90,2,2));
}
// get data and store in a json array
$query = "SELECT * FROM data ORDER BY data_id";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$curcrop = array();
$data_id = $row['data_id'];
$days_to_harvest = $row['days_2_harvest'];
$resolution = $row['resolution'];
//Get type name
$type_id = $row['type_id'];
$type = mysql_query("SELECT * FROM type WHERE type_id=$type_id") or die(mysql_error());
while($typerow = mysql_fetch_array( $type )) {
$curcrop['Type'] = $typerow['type_name'];
}
//Get planting method name
$method_id = $row['method_id'];
$method = mysql_query("SELECT * FROM method WHERE method_id=$method_id") or die(mysql_error());
while($methodrow = mysql_fetch_array( $method )) {
$curcrop['Method'] = $methodrow['method_name'];
}
//Get crop name
$crop_id = $row['crop_id'];
$crop = mysql_query("SELECT * FROM crop WHERE crop_id=$crop_id") or die(mysql_error());
while($croprow = mysql_fetch_array( $crop )) {
$curcrop['Crop'] = $croprow['crop_name'];
}
//calculate the direct sow date
//Only build real date if the planting method is direct sow
if ($method_id == 1){
//check if it's a fall or spring crop type
//spring date
if ($type_id == 1){
$direct_sow_date = $first_frost_date;
$date_int = $row['wks_b4_frost_2_sow'] * 7;
date_sub($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
//fall date
}else{
$direct_sow_date = $last_frost_date;
$date_int = $row['wks_b4_first_frost'] * 7;
date_sub($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
}
}else{
$direct_sow_date = null;
}
$curcrop['SowDirect'] = $direct_sow_date;
//calculate transplant date
if ($method_id == 2){
//check if it's a fall or spring crop type
//spring date
if ($type_id == 1){
$transplant_date = $first_frost_date;
$date_int = $row['wks_b4_last_frost_2_trans'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int days"));
//fall date
}else{
$transplant_date = $last_frost_date;
$date_int = $row['wks_b4_first_frost'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int days"));
}
}else{
$transplant_date = null;
}
//transplant sow date
if ($transplant_date != null){
$date_int_trans = $row['wks_2_grow_trans'] * 7;
date_sub($transplant_date,date_interval_create_from_date_string("$date_int_trans days"));
$curcrop['SowTransplant'] = $transplant_date;
date_add($transplant_date,date_interval_create_from_date_string("$date_int_trans days"));
}else{
$curcrop['SowTransplant'] = null;
}
$curcrop['Transplant'] = $transplant_date;
//begin harvest date
if ($method_id == 1 && $direct_sow_date != null){
date_add($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['BeginHarvest'] = $direct_sow_date;
date_sub($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
}
if ($method_id == 2 && $transplant_date != null){
date_add($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($transplant_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['BeginHarvest'] = $transplant_date;
date_sub($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($transplant_date,date_interval_create_from_date_string("$resolution days"));
}
//end harvest date
if ($method_id == 1 && $direct_sow_date != null){
date_add($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['EndHarvest'] = $direct_sow_date;
date_sub($direct_sow_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($direct_sow_date,date_interval_create_from_date_string("$resolution days"));
date_add($direct_sow_date,date_interval_create_from_date_string("$date_int days"));
}
if ($method_id == 2 && $transplant_date != null){
date_add($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_add($transplant_date,date_interval_create_from_date_string("$resolution days"));
$curcrop['EndHarvest'] = $transplant_date;
date_sub($transplant_date,date_interval_create_from_date_string("$days_to_harvest days"));
date_sub($transplant_date,date_interval_create_from_date_string("$resolution days"));
date_add($transplant_date,date_interval_create_from_date_string("$date_int days"));
}
$crops[] = $curcrop;
}
echo json_encode($crops);
?>
In the first example, you're appending an array of information to the $crops array, but in the second, you append an empty array to the $crops array, and then set a few keys in that same $crops array.
What you need to do is build your "current crop" array with the second method and then append that array to the $crops list, as before:
$curcrop = array();
if($var1 == something) {
$curcrop['Type'] = $value1;
}
if($var2 == something) {
$curcrop['Method'] = $value2;
}else{
$curcrop['Crop'] = $value3;
}
$crops[] = $curcrop;

Sometimes the contents load and sometimes they don't

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?

Categories