PHP/MySQL show last updated/most recent date - php

I have a mysql query that brings in a list of results, say 10, each with its own 'last edited' date, and was wondering if it was possible to display/echo/print ONLY the most recent of these dates using php?
Now I know I could do this with a mysql query, but I need to display all of the available results, but only 1 date, (the most recent).
Hope this makes sense. Any help greatly appreciated. S.
<?php
$availQuery=mysql_query("select * from isavailability");
$availResult=mysql_fetch_array($availQuery);
$date = $availResult['editDate'];
$newDate = date('D dS F Y',strtotime($date));
$time = date('G:i:s',strtotime($date));
echo '<p>This page was last updated on '.$newDate.' at '.$time.'</p>' . PHP_EOL;
while($availR=mysql_fetch_array($availQuery)) {
echo '<tr class="rows">'. PHP_EOL;
echo '<td><p>'.$availR['title'].'</p></td>'. PHP_EOL;
echo '<td>'; if ($availR['availability']==1) { echo $tick; } else { echo $cross; } echo '</td>'. PHP_EOL;
echo '<td>'; if ($availR['availability']==2) { echo $tick; } else { echo $cross; } echo '</td>'. PHP_EOL;
echo '<td>'; if ($availR['availability']==3) { echo $tick; } else { echo $cross; } echo '</td>'. PHP_EOL;
echo '</tr>'. PHP_EOL;
}
?>

It can be done in a single query: SELECT isavailabilit.*, MAX(editDate) AS LastEditDate FROM isavailabilit;
Use it this way in the loop: $availR['LastEditDate']

If your query is ordered by your timestamp then you could just grab the first one - if I understand your question:
$myDate = $myData[0]['myDateColumn'];
foreach($myData as $row)
{
echo $myDate . ' ' . $row['someotherColumn'] . "\n";
}
or something similar? Presuming your results are in an array.

Related

How can i display my preg_match results in various divs so they can have multiple results under the correct heading?

Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)

Display date format as DD MM YYYY in Codeigniter [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 5 years ago.
As you can see my date.of.birth format is Y-m-d, so I hope to change my D.O.B (tarikh lahir) format to d-m-Y,please help.
This is model : Search_model.php
<?php
class Search_model extends CI_Model {
public function get_results($search_term='default')
{
// Use the Active Record class for safer queries.
// $this->load->helper('share_function');
$this->db->select('pesakit.rn,pesakit.nama,pesakit.tarikhlahir,jantina.nama as jantina,agama.nama as agama,bangsa.nama as bangsa');
$this->db->from('lifeline.pesakit as pesakit');
$this->db->join('jantina','jantina.kod = pesakit.jantina');
$this->db->join('agama','agama.kod = pesakit.agama');
$this->db->join('bangsa','bangsa.kod = pesakit.bangsa');
$this->db->where('rn',alphaToNumber($search_term));
// Execute the query.
$query = $this->db->get();
// Return the results.
return $query->result_array();
}
}
This is view : search_results.php
<div>
<?php
foreach ($results as $val)
{
echo 'RN : '; echo numberToAlpha( $val['rn']); echo "<br/>";
echo 'Name : '; echo $val['nama']; echo "<br/>";
echo 'Date.of.Birth : '; echo $val['tarikhlahir']; echo "<br/>";
echo 'Age:' ; echo calculateCurrentAge ($val['tarikhlahir']); echo "<br/>";
echo 'Gender : '; echo $val['jantina']; echo "<br/>";
echo 'Race : '; echo $val['bangsa']; echo "<br/>";
echo 'Religion : '; echo $val['agama'];
}
?>
</div>
Check this code. Hopefully, it will help you.
$dob = "2012-03-08";
echo date("d-m-Y", strtotime($dob));
//output date
08-03-2012
You need to create a function dateFormat in Helper.
function dateFormat($date, $format = 'd-M-Y'){
return date($format, strtotime($date));
}
We can call this :
<td><?php echo dateFormat($val['tarikhlahir']);?></td>
Using above function, date will be returned as its in default parameter.
While it can be changed where we will call this function.
For example :
<td><?php echo dateFormat($val['tarikhlahir'], 'm-d-Y');?></td>
Try not to use the semicolon to concatenate the strings.
Use "Dot" to do this.
echo 'Date.of.Birth : ' . date('d m Y', strtotime($val['tarikhlahir']) . "<br/>";
date('d-m-Y', strtotime($the_date_you_want_to_convert));
http://php.net/manual/en/function.strtotime.php
As per the #Alex answer.
As per my knowledge, there is no separate date function in CodeIgniter.
You can use PHP date function.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.strtotime.php
$val['tarikhlahir']='1959-01-30';
$date=date('d-m-Y',strtotime($val['tarikhlahir']));
echo $date;
Please replace your the code as given below
<div>
<?php
foreach ($results as $val)
{
echo 'RN : '; echo numberToAlpha( $val['rn']); echo "<br/>";
echo 'Name : '; echo $val['nama']; echo "<br/>";
$originalDate = $val['tarikhlahir'];
$newDate = date("d-m-Y", strtotime($originalDate));
echo 'Date.of.Birth : '; echo $newDate; echo "<br/>";
echo 'Age:' ; echo calculateCurrentAge ($val['tarikhlahir']); echo "<br/>";
echo 'Gender : '; echo $val['jantina']; echo "<br/>";
echo 'Race : '; echo $val['bangsa']; echo "<br/>";
echo 'Religion : '; echo $val['agama'];
}
?>
</div>
This may help you..Thanks!
since nobody mentioned it - imho the safest way to do this is the DateTime::createFromFormat function.
Something like that should work
<div>
<?php
foreach ($results as $val)
{
$objDateTime = DateTime::createFromFormat('Y-m-d', $val['tarikhlahir']);
echo 'RN : '; echo numberToAlpha( $val['rn']); echo "<br/>";
echo 'Name : '; echo $val['nama']; echo "<br/>";
echo 'Date.of.Birth : '; echo $objDateTime->format('d-m-Y'); echo "<br/>";
echo 'Age:' ; echo calculateCurrentAge ($val['tarikhlahir']); echo "<br/>";
echo 'Gender : '; echo $val['jantina']; echo "<br/>";
echo 'Race : '; echo $val['bangsa']; echo "<br/>";
echo 'Religion : '; echo $val['agama'];
}
?>
</div>

foreach() Loop Outputting Data and Creating Layout

I am currently trying to create a class schedule which I pull from my Sql Server database with PHP and I am trying to get the layout output as well as the data as I am grouping the resources.
These groupings are nested such as:
-DAY
--TIME
---CLASS
----STUDENTS
And should output like this:
However, I am getting this:
My current output is working, however, it is only on the first loop, then everything goes haywire. I am assuming there is an erroneous </div> tag somewhere in my code yet I cannot for the life of me find it.
My php code is a function that is delcare as such:
<div class="mainScheduleWrapper">
<?php daySchedule(); ?>
</div>
My php code is as such:
function daySchedule() {
global $conn;
$dayScheduleQuery = 'SET DATEFIRST 1
SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT, INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB
FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID
WHERE [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))
ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';
// COUNTERS
$t = 0;
$i = 0;
//VARIABLES FOR DAY SCHEDULE
$classDay = NULL;
$classTime = NULL;
$classInstructor = NULL;
$closeClass = false;
$closeAll = false;
$queryConnector = $conn->query($dayScheduleQuery);
foreach ($queryConnector as $schedule) {
// CLASS DAY HEADER
if ($classDay != $schedule['DAY']) {
echo '<div class="grid-1">';
echo '<h1>' . $schedule['DAY'] . '</h1>';
echo '</div><!-- Day closed! -->';
$classDay = $schedule['DAY'];
}
// CLASS TIME HEADER
if ($classTime != $schedule['CLASSTIME']) {
if($classTime != $schedule['CLASSTIME'] && $t > 0) {
$closeAll = true;
goto closeAll;
}
echo '<div class="grid-12-noGutter scheduleContainer">'; //NON-CLOSED
echo '<h1>' . 'T = ' . $t . '</h1>';
echo '<div class="grid-middle-center col scheduleTimeTab">';
// FIX 3 DIGIT MILITARY TIME
if (strlen($schedule['CLASSTIME']) < 4) {
$classScheduleTime = '0' . $schedule['CLASSTIME'];
} else {
$classScheduleTime = $schedule['CLASSTIME'];
}
echo '<p>' . date('g:i A', strtotime($classScheduleTime)) . '</p>';
echo '</div>'; //CLOSE TIME TAB
echo '<div class="innerSchedule">'; // NON-CLOSED
$classTime = $schedule['CLASSTIME'];
$t += 100;
}
// INSTRUCTOR HEADER
if ($classInstructor != $schedule['INSTRUCTOR']) {
if ($classInstructor != $schedule['INSTRUCTOR'] && $i > 0) {
$closeClass = true;
goto closeClassWrapper;
}
echo '<div class="classWrapper">';
echo '<h1>' . 'I =' . $i . 'T = ' . $t . '</h1>';
echo '<div class="grid-3-middle classHeader">';
echo '<div class="col classHeaderCell' . classLevelColour($schedule['CLASSLEVEL']) . '">' . $schedule['CLASSLEVEL'] . '</div>';
echo '<div class="col classHeaderCell">' . $schedule['INSTRUCTOR'] . '</div>';
echo '<div class="col classHeaderCell">Max' . ' ' . $schedule['MAXSTUDENT'] . '</div>';
echo '</div>';
echo '<div class="grid-4-middle" id="studentHeaders">';
echo '<div class="col"><h6>Student Name</h6></div>';
echo '<div class="col"><h6>Student Birthday</h6></div>';
echo '<div class="col"><h6>Class Level</h6></div>';
echo '<div class="col"><h6>Attendance</h6></div>';
echo '</div>';
$classInstructor = $schedule['INSTRUCTOR'];
$i += 100;
}
echo '<div class="grid-4 studentRow">';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTFIRST'] . ' ' . $schedule['STUDENTLAST'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['STUDENTDOB'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">' . $schedule['CLASSLEVEL'] . '</span>';
echo '</div>';
echo '<div class="col">';
echo '<span class="studentCell">--</span>';
echo '</div>';
echo '</div>';
// GOTO TAGS
closeClassWrapper: {
if ($closeClass === true) {
echo '</div>';
$closeClass = false;
$i = 0;
}
}
closeAll: {
if ($closeAll === true) {
echo '</div>';
echo '</div>';
echo '</div>';
$closeAll = false;
$t = 0;
$i = 0;
}
}
}
}
Any help would be greatly appreciated - even if it's to tell me I'm going about it the completely wrong way.
Kindest Regards
Michael Z
I wouldn't say you're going about it the completely wrong way, but a few red flags jumped out at me in your code.
The use of goto jumping is bad practice. It butchers your program flow and forces you to segregate tasks that shouldn't be kept apart. You marked the sections of code "// NON CLOSED" when there was a </div> missing, is there any purpose for that? How do you know the goto sections are reliable?
When you echo something like <div class="col">, without escaping the double-quotes (as in \" for every " character), it can be problematic. Your code can get mangled or misinterpreted, both on the PHP end or on the HTML end.
Like others have said, the use of PHP may be overkill here. Besides just sending the JSON, the rest could be handled with JavaScript.

How To Parts Of Speech Only One Time In PHP

I want to show only one time the heading of parts of speeches for example when user enter the word "Spell" all the parts of speeches and its meaning come every time .
The headings are repeating multiple times . i want to print only one time
There should be a heading Of Noun,Verb,Adjective etc..
like this
Noun.
Verb.
adjective.
this is my code
while($row=mysql_fetch_array($sql)){
echo "<div id='wordid' style='display:none'>".$row["wordid"]."</div>";
echo $count++." : ".$row['definition']. " ";
if($row['pos']=="n"){
echo "(Noun) <br/>";
}
if($row['pos']=="s"){
echo "(Subject) <br/>";
}
if($row['pos']=="p"){
echo "(Proverb) <br/>";
}
if($row['pos']=="a"){
echo "(Adjective) <br/>";
}
if($row['pos']=="v"){
echo "(Verb) <br/>";
}
}
You can keep track of what the last wordid was and only echo the header if it changed.
// initialize to avoid notices
$lastWordId = '';
while($row=mysql_fetch_array($sql)){
if ($lastWordId != $row['wordid']) {
echo "<div id='wordid' style='display:none'>".
$row["wordid"].
"</div>";
$lastWordId = $row['wordid'];
}
echo $count++." : ".$row['definition']. " ";
if($row['pos']=="n"){
echo "(Noun) <br/>";
}
if($row['pos']=="s"){
echo "(Subject) <br/>";
}
if($row['pos']=="p"){
echo "(Proverb) <br/>";
}
if($row['pos']=="a"){
echo "(Adjective) <br/>";
}
if($row['pos']=="v"){
echo "(Verb) <br/>";
}
}

Listing diary events grouped by days in PHP/MySQL

I'm trying to list diary events in PHP from a MySQL database, but grouped by days. I'll explain.
This is a screenshot of what I have so far:
As you can see there are two diary events for the 23rd October 2012 and is showing two calendar icons/representations/whatever's. I actually want it to show one calendar icon on the left but list all of that days events on the right, until the next day - as seen in my a̶r̶t̶i̶s̶t̶s̶ idiots impression below:
This is the code I have just written, could somebody please point me in the right direction:
$SQL = "SELECT entry_id, entry_title, entry_body, entry_date, entry_day, entry_month, entry_year ";
$SQL .= "FROM pages_diary WHERE entry_month = :this_month AND entry_year = :this_year ";
$SQL .= "ORDER BY entry_date DESC;";
// PDO stuff
if ($STH->rowCount() > 0) {
while($row = $STH->fetch()):
$this_db_month_word = mktime(0, 0, 0, $row['entry_month']);
$this_db_month_word = strftime("%b", $this_db_month_word);
echo '<div class="diary_events_item" id="diary_events_item_'.$row['entry_id'].'">';
echo '<div class="diary_events_item_left">';
echo '<div class="calendar_wrap">';
echo '<div class="calendar_wrap_top">';
echo $this_db_month_word;
echo '</div>';
echo '<div class="calendar_wrap_bottom">';
echo str_pad($row['entry_day'],2,'0',STR_PAD_LEFT);;
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="diary_events_item_right">';
echo '<strong>'.htmlspecialchars($row['entry_title']).'</strong><br>';
echo '<p>'.htmlspecialchars($row['entry_body']).'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
endwhile;
} else {
echo '<p>There are no diary entries logged for <strong>'.$this_month_word.' '.$this_year.'</strong>.</p>';
}
Not looking for exact code (although that would be spiffing), just an explanation would do, I'm sure I can work it out from that.
THE FIX
At the end of the WHILE loop, I added:
$last_db_day = $row['entry_day'];
And then wrapped the calendar item in:
if ($last_db_day != $row['entry_day']) {
echo '<div class="calendar_wrap_top">';
echo $this_db_month_word;
echo '</div>';
echo '<div class="calendar_wrap_bottom">';
echo str_pad($row['entry_day'],2,'0',STR_PAD_LEFT);;
echo '</div>';
}
As you loop over your resultset from the database, keep track of the last entry_date that you've seen and only output a new calendar icon if the current record is for a different date.
I usually do this as follows:
if ($STH->execute()) {
// output headers
$row = $STH->fetch();
while ($row) {
$current_date = $row['entry_date'];
// output $current_date initialisation
do {
// output event $row
} while ($row = $STH->fetch() and $row['entry_date'] == $current_date);
// output $current_date termination
}
// output footers
}
Although I would go the other way around and embed the PHP within the HTML rather then the other way around, here is what I would do using your code:
$SQL = "SELECT entry_id, entry_title, entry_body, entry_date, entry_day, entry_month, entry_year ";
$SQL .= "FROM pages_diary WHERE entry_month = :this_month AND entry_year = :this_year ";
$SQL .= "ORDER BY entry_date DESC;";
// PDO stuff
if ($STH->rowCount() > 0) {
$loopDay = '';
while($row = $STH->fetch()):
if ($row['entry_day'] != $loopDay) {
$loopDay = $row['entry_day'];
$changed = true;
}
$this_db_month_word = mktime(0, 0, 0, $row['entry_month']);
$this_db_month_word = strftime("%b", $this_db_month_word);
echo '<div class="diary_events_item" id="diary_events_item_'.$row['entry_id'].'">';
echo '<div class="diary_events_item_left">';
if ($changed) {
echo '<div class="calendar_wrap">';
echo '<div class="calendar_wrap_top">';
echo $this_db_month_word;
echo '</div>';
echo '<div class="calendar_wrap_bottom">';
echo str_pad($row['entry_day'],2,'0',STR_PAD_LEFT);;
echo '</div>';
echo '</div>';
} else {
echo ' ';
}
echo '</div>';
echo '<div class="diary_events_item_right">';
echo '<strong>'.htmlspecialchars($row['entry_title']).'</strong><br>';
echo '<p>'.htmlspecialchars($row['entry_body']).'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
$changed = false;
endwhile;
} else {
echo '<p>There are no diary entries logged for <strong>'.$this_month_word.' '.$this_year.'</strong>.</p>';
}

Categories