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
Related
I have made a code where I get all nubers in the month then I am adding on events from my database. I need the numbers to come from the database in $sqldates I am now only getting array as when I echo the $sqldates. I have 4, 10, 22 and 26 in my database now.
This is what I am getting now look at the picture
enter image description here
This is the result I want look at this picture.
enter image description here
How do I get the results from my database as picture 2 shows? Pleas help how to get the numbers from array.
<table>
<?php
//database connent
include 'con.php';
//get day from event
$sql = "SELECT day, color FROM events";
$result = mysqli_query($con, $sql);
$sqldates = array(array('day', 'color_value'), array('date_value', 'color_value'), array('date_value', color_value));
while($row=mysqli_fetch_array($result)){
array_push($sqldates, $row['day'], $row['color'] );
echo $row['day'];
}
$counter = 0;
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo "<td width=50 bgcolor='#{$sqldates[$counter][1]}'>$sqldates[$counter][0]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}
?>
</table>
For your updated question this should be good guide:
<table>
<?php
//database connect
include 'con.php';
//get day from event
$sql = "SELECT day, color FROM events";
$result = mysqli_query($con, $sql);
$sqldates = array();
$colors = array();
while($row=mysqli_fetch_array($result)){
array_push($sqldates, $row['day']);
array_push($colors, $row['color']);
}
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
$counter = 0;
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo "<td width=50 bgcolor='$colors[$counter]'>$sqldates[$counter]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}
?>
</table>
Note that you need to have defined color for each day, otherwise you will get "Undefined offset" notice.
You are trying to echo an array. Instead you should echo a value from that array with specified index. If I am not wrong, this should work:
//first day
$firstday = '1';
$two = cal_days_in_month(CAL_GREGORIAN, 8, 2018); // 31
//for loop get all day in month
$counter = 0;
for ($number = $firstday; $number <= $two; $number++)
if (in_array($number , $sqldates)) {
echo"<td width=50 bgcolor='#f44242'>$sqldates[$counter]</td>";
$counter++;
} else {
echo"<td width=50 bgcolor='#1e8e8e'>$number</td>";
}
I'm trying to echo a random date in a PHP loop, the code works for "if the post is 3 months old", then I want to get today's date, and minus the "random" number, eg will echo a date based on this number.
Everything is working, but not the $number. Can someone please tell me where I'm going wrong?
<?php
$post_age = date('U') - get_the_time('U');
if($post_age > 7884000 ) {
?>
<?php $number = 'UniqueRandomNumbersWithinRange(0,25,5)'; ?>
<?php echo date('jS F', strtotime("now -'.$number.' days") ); ?>
<?php } else {?>
<?php } ?>
with function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
Thanks :)
Two issues that I see there which are likely causing the issue, there are two occasions where you are turning things into strings but don't want to:
for
this isn't running the function because it's between single quotes ' ' so you want to remove them
<?php $number = UniqueRandomNumbersWithinRange(0,25,5); ?>
and for
You are mixing different types of quotes and so $number isn't really being called. You likely want to adjust it to something like:
<?php echo date('jS F', strtotime("now -".$number." days") ); ?>
You are confusing strings and functions several times in your code, as James' answer says.
Also, your UniqueRandomNumbersWithinRange() function returns an array. This cannot be written to a string.
<?php
$post_age = date('U') - get_the_time('U');
if($post_age > 7884000) {
$number = fetchRandoms(0, 25, 5);
echo date('jS F', strtotime("now -" . $number . " days") );
} else {
// la dee da
}
function fetchRandoms($min, $max, $amt) {
$result = '';
for ($i = 0; $i < $amt; $i++) {
$result .= mt_rand($min, $max);
}
return $result;
}
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.
I'm building an interactive timeline that loads in films and calculates the difference between their release dates, thus displaying "days" where there isn't any film release to create a timeline effect. However I have some films that are released on the same date. I don't want to repeat the date for these films over and over again, rather just display the date for the first film in like a group effect.
I have manipulated an if statement that loops through the table and checks whether the date is the same as the previous row's date.
http://ignitethatdesign.com/CheckFilm/test_search.php
However how would I use PHP to only display the date for the first film in a group of films with the same date?
I'm using a complex loop system, here is the full code
<?php
$last_value = null;
echo "<div class=\"timeline\">";
$pNumber = 0;
while ($row = mysql_fetch_assoc($sql)) {
if (!is_null($last_value)) {
$pNumber++;
$a = new DateTime($row['FilmRelease']);
$film_date = $row['FilmRelease'];
$film_name = urldecode($row['FilmName']);
$film_desc = urldecode($row['Synopsis']);
echo "<div id=\"t".$pNumber."\"><p class=\"everyday\">".$film_name."</div>";
if (empty($film_desc)) {
echo "<div id=\"b".$pNumber."\" style=\"font-size:12px;\">No film information for ".$film_name."</div>";
}
else
{
echo "<div id=\"b".$pNumber."\" style=\"font-size:12px;\">".$film_desc."</div>";
}
?> <script type="text/javascript">
$("#b<?php echo $pNumber ?>").hide();
$("#t<?php echo $pNumber ?>").click(function() {
$("#b<?php echo $pNumber ?>").fadeToggle("slow");
});
</script>
<?php
$interval = $a->diff(new DateTime($last_value));
//echo $interval->format('%d days');
$b = new DateTime($last_value);
$i = 0;
}
if ($b == $a)
{
echo "same date as above";
} else
{
echo "This date is different";
}
$howManydays = $interval->days;
for ( $i; $i < $howManydays; $i++) {
echo "<p class=\"day\"></p>";
}
$last_value = $row['FilmRelease'];
}
echo "<div id=\"end\"></end>";
echo "</div>";
?>
Any help would be greatly appreciated :)
Simple example:
$lastDate = null;
while (...) {
$currentDate = date('Y-m-d', strtotime($film['date']));
if ($currentDate != $lastDate) {
echo "<h1>$currentDate</h1>";
}
$lastDate = $currentDate;
// output film details
}
This will give you something like:
2012-04-01
Film A
Film B
2012-04-02
Film C
2012-04-05
Film D
Film E
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;
}