I have recently noticed on my website that a news page is repeating news articles from all "May"'s in the database (you will notice by looking here: www.darlingtontowntwinning.co.uk/news_&_events)
I know that the coding is messy and possibly out of date, however, the website was built for us, and I don't have the skills (yet - I am learning!) to change the entire website at this time.
Is there a way to stop this from occuring - since I believe I have already got a limit of one of each record to display:
<div id="right" class="news">
<h3>Archive</h3>
<? $news=$session->getNews("","","",1);?>
<? while($article=mysql_fetch_array($news)){?>
<?
$date = $article['thedate'];
$year = date('Y', $date);
$month = date('F', $date);
?>
<h4><?=$month." - ".$year;?></h4>
<nav class="small">
<? $innernews=$session->getNews("",$month,$year);?>
<? while($innerarticle=mysql_fetch_array($innernews)){?>
<a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a>
<? }?>
</nav>
<? }?>
</div>
Get news function is:
function getNews($title,$month,$year,$group){
global $database;
return $database->getNews($title,$month,$year,$group);}
$database->getNews function is:
//get news
function getNews($title,$month,$year,$group){
if($title){
$q=$this->query("SELECT * FROM ".TBL_NEWS." WHERE ftitle = '$title'" );
return mysql_fetch_array($q);
}else if($year && $month){
$q=mysql_query("SELECT * FROM ".TBL_NEWS." WHERE (FROM_UNIXTIME(thedate, '%Y') = '$year') AND (FROM_UNIXTIME(thedate, '%M') = '$month') ORDER BY thedate DESC");
return $q;
}else if($group){
$q=$this->query("SELECT * FROM ".TBL_NEWS." GROUP BY (FROM_UNIXTIME(thedate, '%Y')),(FROM_UNIXTIME(thedate, '%M')) ORDER BY thedate DESC" );
return $q;
}else{
$q=$this->query("SELECT * FROM ".TBL_NEWS." ORDER BY thedate DESC" );
return $q;
}
}
The code appears to be working
//get news from group 1
$news=$session->getNews("","","",1);
// for each article work out the date
while($article=mysql_fetch_array($news))
$date = $article['thedate'];
$year = date('Y', $date);
$month = date('F', $date);
...
// then select everything again after working out the date (odd way of doing it)
$innernews=$session->getNews("",$month,$year);
// and output each
So, because there are two event in May, it's outputting the header twice. Let me go over that...
Get news grouped by date (allegedly)
June, just 1 article
1:
Output the header
Select the articles
Output the article
May, 2 articles
1:
Output the header
Select the articles
Output the article
2:
Output the header
Select the articles
Output the article
This group by SELECT * FROM ".TBL_NEWS." GROUP BY (FROM_UNIXTIME(thedate, '%Y')),(FROM_UNIXTIME(thedate, '%M')) ORDER BY thedate DESC is not behaving as expected and is returning two results for May
Try this code
<div id="right" class="news">
<h3>Archive</h3>
<?
$news=$session->getNews();
$bydate=array(); // articles by date
while($article=mysql_fetch_array($news)){
$k=date('YF', $date);
if (!isset($bydate[$k])) $bydate[$k]=array(); // create sub array
$bydate[$k][]=$article; // push article to this sub array
}
foreach ($bydate as $date->$articles){ // run through top array
?><h4><?= substr($date,4) . " - " . substr($date,0,4); ?></h4><nav class="small"><?
foreach ($articles as $innerarticle){ // now each article within this date
?><a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a><?
}
?></nav><?
}
?></div>
and please change
function getNews($title,$month,$year,$group){
to
function getNews($title=NULL, $month=NULL, $year=NULL, $group=NULL){
Welp. There's your problem.
Your function says, if($title). Since $title comes in as a required parameter in the function, I think PHP is registering it as, yes, that's a variable that is set. So, basically what happens, then, is you're getting back a mysql_fetch_array result, which you are then running mysql_fetch_array for a second time.
Try:
//in your function getNews()
if($title){
$q=$this->query("SELECT * FROM ".TBL_NEWS." WHERE ftitle = '$title'" );
return $q;
}
//rest of function down here
That could work. The issue I see is, doing that, you WILL CAUSE ISSUES ANYWHERE ELSE THAT FUNCTION IS CALLED. So be careful! The fix above is the fix to ensure you get code into a better state. If you want a hack, try this:
<? $innernews=$session->getNews("",$month,$year);?>
<? foreach($innernews as $innerarticle) {?>
<a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a>
<? }?>
The foreach loop should give you what you want!
Related
Is it possible to create dates with variables from the post? To goal is to select a date range based on a form. Here's what I have so far:
<?php
include 'inc/connect.php';
if(isset($_POST['rapport-taxes']))
{
$year=$_POST['year'];
$Q2_start_create=date_create($year"-04-01");
$Q2_end_create=date_create($year"-06-30");
$Q2_start=date_format($Q2_start_create,"Y/m/d");
$Q2_end=date_format($Q2_end_create,"Y/m/d");
$test="SELECT * FROM devis where `fp_date` > '$Q2_start' and `fp_date` < '$Q2_end'";
$query=mysqli_query($conn, $test);
echo $query;
}
?>
Any ideas?
There can be hundreds of way but I am just helping you in what you are doing.
You missed concatenation of year, in the below line.
$Q2_start_create=date_create($year"-04-01");
//$year and "-04-01", to concatinate both you need to put a .
See the below code, run it once. echo is just to check so remove it later.
$year="2005";
$Q2_start_create=date_create($year."-04-01");
$Q2_start=date_format($Q2_start_create,"Y/m/d");
echo $Q2_start;
PHP doesn't enforces date datatype. date_format(); will be returning string so you could just build a string and pass it to the query as long as the code you have posted is the only thing you want to get done.
<?php
include 'inc/connect.php';
if(isset($_POST['rapport-taxes']))
{
$year=$_POST['year'];
$Q2_start= $year . "/04/01";
$Q2_end= $year . "/06/30";
$test="SELECT * FROM devis where `fp_date` > '$Q2_start' and `fp_date` < '$Q2_end'";
$query=mysqli_query($conn, $test);
echo $query;
}
?>
I am trying to create a script where if the date is later than today then it will display an item from the table in MySQL.
$query = $dbc->query("SELECT event_id, name, location, image, DATE_FORMAT(Date, '%d-%b-%Y') AS Date, Date as FormatDate
FROM events
ORDER BY FormatDate ASC
");
$results = $query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
$name = $row['name'];
$image = $row['image'];
$location = $row['location'];
$Date = $row['Date'];
$Date = strtotime($Date);
$Date = date('d-M-Y', $Date);
$Data = explode("-", $Date);
if (strtotime($Date) >= time()){
$page->body("
<div class=\"event\">test
<img src=\"$image\" alt=\"$name\" class=\"event_image\"/>
<p class=\"event_title\">$name</p>
<p class=\"event_location\">$location</p>
<p class=\"event_time\">$Data[0] $Data[1] $Data[2]</p>
</div>
");
}else{
$page->body ("
<!-- alrge grey text 100% span -->
<div class=\"event\">
<p>There are currently no events happening.</p>
</div>
");
}
}
}
When I add an event to the table with a later date than today it adds successfully and the script runs and I can see the event printed out on the page because the date if greater than time().
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
I am stumped as to why the else statement doesn't bring back the failed notification if there is nothing in the table that is later than today.
Any help much appreciated.
But if I clear the MySql table of all events then it doesn't bring back the else statement "There are currently no events happening".
The while statement will only execute if there are rows to process. Since you've cleared the table, it will never enter the while loop, and the else branch will never be encountered.
Because there are no rows to fetch and your code is not going inside while loop when your table is empty.
HTH!
I am using the code below to generate a simple HTML table that displays the next 90 calendar days. Each day is a row in this simple table.
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td></tr>\n";
}
echo "</table>";
Also, I have a MySQL table with the following fields:
event varchar(1000)
datescheduled date
How can I make a second column in the aforementioned HTML table, containing "event" from the MySQL table, matched by date?
This can be tackled in numerous ways. Consider this example:
PHP
<?php
$con = mysqli_connect("localhost","dbuser","dbpass","database");
$query = mysqli_query($con, "SELECT * FROM event");
// First build the array of events, put the dates in keys, then the values as events
$events = array();
while($result = mysqli_fetch_assoc($query)) {
$events[$result['datescheduled']] = $result['event'];
}
?>
// Structure should be something like this:
Array
(
[2014-05-02] => Day of lorem
[2014-06-02] => Day of ipsum
[2014-07-02] => Day of days
)
HTML
<!-- the compare selected values on the current loop, check its keys -->
<?php $now = time(); ?>
<table border="1" cellpadding="10">
<?php for($i=0;$i<90;$i++): ?>
<?php $thisDate = date("Y-m-d", $now + ($i*86400)); ?>
<tr>
<td><?php echo $thisDate; ?></td>
<td><?php echo array_key_exists($thisDate, $events) ? $events[$thisDate] : ''; ?></td>
</tr>
<?php endfor; ?>
</table>
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td>";
$result_set = mysql_query("SELECT event FROM eventTable WHERE datescheduled = STR_TO_DATE('{$thisDate}','%d/%m/%Y')'",$connection);
$result = mysql_fetch_assoc($result_set);
echo "<td>{$result['event']}</td></tr>\n";
}
echo "</table>";
Its worth noting that you will need to use a string to date function in mysql depending on how the date is stored.
Edit: in case you need further hand holding, here is the STR_TO_DATE function done for you.
STR_TO_DATE('{$thisDate}','%d/%m/%Y')
I have edited my code above to reflect this as to not strain your brain.
Even tossed in some screenshots of the table and the output, just because you were kind of an ass in your comment. With 5 years of experience i would have thought you would know how to echo out a simple table like this, or at the very least, have a little common courtesy when someone tries to help you.
I have a mysql database with a field called DATE, storing data as a date. I am trying to get the php date to select records for the next 31 days from the current date.
This is what I have...
$start_THISMONTH = "-1";
if (isset($to_date)) {
$start_THISMONTH = $to_date;
}
$finish_THISMONTH = "-1";
if (isset($from_date)) {
$finish_THISMONTH = $from_date;
}
mysql_select_db($database_WHTSON, $WHTSON);
$query_THISMONTH = sprintf("SELECT * FROM CALENDAR WHERE DATE BETWEEN %s AND %s AND APPROVED = 1 ORDER BY DATE ASC", GetSQLValueString($start_THISMONTH, "date"),GetSQLValueString($finish_THISMONTH, "date"));
$THISMONTH = mysql_query($query_THISMONTH, $WHTSON) or die(mysql_error());
$row_THISMONTH = mysql_fetch_assoc($THISMONTH);
$totalRows_THISMONTH = mysql_num_rows($THISMONTH);
-
The code to set up the two variables is
$from_date = date("Y-m-j");
$to_date = date('Y-m-j', strtotime("+31 days"));
And my php code in the body is
<h4><strong><font color="#FF0000"><?php echo $row_THISMONTH['EVENT_NAME']; ?></font></strong></h4>
<?php $date = date_format($row_THISMONTH['DATE'], 'jS F'); ?>
<h5><em><?php echo $date; ?>, <?php echo $row_THISMONTH['TIMES']; ?><br />
<?php echo $row_THISMONTH['LOCATION_ADDRESS']; ?>, <?php echo $row_THISMONTH['LOCATION_TOWN']; ?> <?php echo $row_THISMONTH['LOCATION']; ?></em><br />
</h5>
<p><?php echo $row_THISMONTH['EVENT_DETAILS']; ?><br />
</p>
No results are showing up. This is a new build database, and only one record is in there, with a date of Valentines Day. If I change the code to a simple "find all records" query it shows up great (though the date_format doesn't display a date.
This is my nemesis, please help me understand what I've done wrong?
If you have a date field column in mysql(YYYY-MM-DD) then try date('Y-m-d') instead of date('Y-m-j')
I have been staring at this for so long, but I think I have found one answer. I tried to be logical and use $to_date and $from_date, and then put them in the wrong order in the query. So although I haven;t actually solved the issue, I thinnk the issue is my untidyness on this occasion. I learnt a lot from the discussion too, thank you very much - time for a cleen sheet and a slower pace :)
I have a loop that runs through returned rows from a MySQL query and performs commands.
When the data is displayed on the webpage (seen at the end of the pasted code), the requested_date (from the $result_dec query) is cycling through correctly, but the memPayout(from the $emailcompleted query) is not. Where it shows the memPayout it is just listing the same number for each date.
When I run this in phpmyadmin, I see that different dates have different memPayouts..so I know there is a bug here.
I appreciate the help.
UPDATE: I've updated the old code with the new one that I adjusted. I tried to wrap the email earnings query with the original foreach. I also removed the unnecessary extra bgcolor switch. The result on my webpage is still the same as before. Any more advice is really appreciated.
<?php
//--------------------- Code for Decline TRANSACTION --------------------------------------
$u_id = $_SESSION['user_ses']['id'];
$result_dec = #mysql_query("(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.requested_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.requested_status='declined' group by trv.tr_user_id, trv.requested_date order by trv.requested_date asc )
union all
(select trv.tr_user_id , usr.full_name ,usr.email , usr.paypal , trv.click_request_date, trv.requested_status, trv.click_payment_status, trv.tracking_id
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and usr.id=trv.tr_user_id and usr.id='1454'
and trv.payment_status='pending' and trv.click_payment_status='declined' group by trv.tr_user_id, trv.click_request_date order by trv.requested_date asc ) ");
$nr = mysql_num_rows($result_dec);
$categories_d = array();
while($row = mysql_fetch_array($result_dec))
{
$categories_d[] = $row;
}
if(count($categories_d)>0)
{
$counter=0;
foreach($categories_d as $index=>$rec)
{
$counter++;
if ($counter % 2 == 0)
{
$bgcolor = "#FFFFFF";
}
else
{
$bgcolor = "#F5F7D9";
}
$userId=$rec['tr_user_id'];
$EmailCompletedOffer=#mysql_query("select off.member_amount as memPayout
from tbl_trackvalue as trv ,tbl_tracking as t , tbl_offers as off , tblusers as usr
where t.id=trv.tracking_id and off.id=t.offer_id and off.offer_type='mailchimp' and usr.id=trv.tr_user_id and
trv.tr_user_id=$userId and trv.requested_date='".$requested_date."' and trv.payment_status='pending' and trv.total_conversion !=0 and trv.requested_status='declined' ");
$rowemailEarn=#mysql_fetch_array($EmailCompletedOffer);
$totalEmailEarnAmount1=$rowemailEarn['memPayout'];
?>
<div class="datarow_his">
<div class="his_onecol1"><?php echo '$'. $totalEmailEarnAmount1;?> </div>
<div class="his_onecol1"> <?php echo "Declined"; ?> </div>
<div class="his_onecol2"><?php echo date("M j,Y " ,strtotime($rec['requested_date']));?></div>
<!--<div class="his_onecol1"><?php //echo date("M j,Y " ,strtotime($rec['paid_date']));?></div>-->
</div>
<p><?php echo $totalEmailEarnAmount1?></p>
<?php /*}
} */
}
}
?>
Your code roughly looks like this:
fetch categories
if(categories not empty) {
foreach(category) {
set $bgcolor and $userId (has no effect)
}
get query results for the last $userID and set $totalEmailEarnAmount1
if(categories not empty) {
foreach(category) {
set $bgcolor again (has no effect)
generate a div using $totalEmailEarnAmount1
}
}
}
Since you set $totalEmailEarnAmount1 outside the final foreach, it has the same value on every iteration of the loop.
(If you indent your code in a way that is consistent with its structure, errors like this will become obvious. The messy indentation makes it hard for you to see what is going on.)