Welcome Guest, Not a member yet? Register   Sign In
Code: Show last 5 months (with number of messages written in that month)
#1

[eluser]Callista[/eluser]
Hi,

for my job i'm making a news/blog page.
on the top it show 3 tables.
first table had 6 titles of the last 6 messages.
second table has 5 months in it with the number of messages written in that month behind it
Last table has de 6 most populair tags.

I got every thing working but the code for the months is a little bit big and messy. So i was wandering if anyone had an idea how i could get this cleaner.


CONTROLLER
Code:
function template_2($pagina_ID)
{
$count_all_news = $this->Basis_model->count_all_nieuws();
$this_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),date("Y")));
        
$month_01 = date('m', mktime(0,0,0,date("m"),date("d"),date("Y")));
$month_02 = date('m', mktime(0,0,0,($month_01-1),date("d"),date("Y")));
$month_03 = date('m', mktime(0,0,0,($month_01-2),date("d"),date("Y")));
$month_04 = date('m', mktime(0,0,0,($month_01-3),date("d"),date("Y")));
$month_05 = date('m', mktime(0,0,0,($month_01-4),date("d"),date("Y")));
      
$that_year    = $this->get_that_year($month_01, $month_02, $month_03, $month_04, $month_05);

$monthname = $this->get_month_name();
        
$data['showmonth_01'] = $monthname[$month_01]."  (". $this->Basis_model->count_month_01($month_01, $this_year).")";
$data['showmonth_02'] = $monthname[$month_02]."  (". $this->Basis_model->count_month_02($month_02, $that_year).")";
$data['showmonth_03'] = $monthname[$month_03]."  (". $this->Basis_model->count_month_03($month_03, $that_year).")";
$data['showmonth_04'] = $monthname[$month_04]."  (". $this->Basis_model->count_month_04($month_04, $that_year).")";
$data['showmonth_05'] = $monthname[$month_05]."  (". $this->Basis_model->count_month_05($month_05, $that_year).")";
$data['archief'] = $count_all_news;


$this->load->view('basis/template2', $data);

}


function get_that_year($maand_01, $maand_02, $maand_03, $maand_04, $maand_05)
{
$this_year    = date('y', mktime(0,0,0,date("m"),date("d"),date("Y")));
        
if     ($maand_02 > $maand_01){$that_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),($this_year-1)));}
if     ($maand_03 > $maand_01){$that_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),($this_year-1)));}
if     ($maand_04 > $maand_01){$that_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),($this_year-1)));}
if     ($maand_05 > $maand_01){$that_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),($this_year-1)));}
else{$that_year    = "'".date('y', mktime(0,0,0,date("m"),date("d"),date("Y")));}
        
return $that_year;
}

function get_maand_naam()
{
$maandnaam = array('01' => 'Januari','02' => 'Februari','03' => 'Maart','04' => 'April','05' => 'Mei','06' => 'Juni','07' => 'Juli',
                   '08' => 'Augustus','09' => 'September','10' => 'Oktober','11' => 'November','12' => 'December');
        
return $maandnaam;
}


MODEL

Code:
function count_month_01($month_01, $this_year)
    {
        $this->db->select('nieuws_datum_maand');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$month_01);
        $this->db->where("nieuws_datum_jaar",$this_year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }
    
    function count_month_02($month_02, $that_year)
    {
        $this->db->select('nieuws_datum_maand');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$month_02);
        $this->db->where("nieuws_datum_jaar",$that_year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }
    
    function count_month_03($month_03, $that_year)
    {
        $this->db->select('nieuws_datum_maand');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$maand_03);
        $this->db->where("nieuws_datum_jaar",$that_year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }
    
    function count_month_04($month_04, $that_year)
    {
        $this->db->select('nieuws_datum_maand');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$month_04);
        $this->db->where("nieuws_datum_jaar",$that_year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }
    
    function count_month_05($month_05, $that_year)
    {
        $this->db->select('nieuws_datum_month');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$month_05);
        $this->db->where("nieuws_datum_jaar",$that_year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }


VIEUW

Code:
<div class="nieuwslist">
<ul>
<li><a href="#" class="list">&lt;?php echo $toonmaand_01;?&gt;</a></li>
<li><a href="#" class="list">&lt;?php echo $toonmaand_02;?&gt;</a></li>
<li><a href="#" class="list">&lt;?php echo $toonmaand_03;?&gt;</a></li>
<li><a href="#" class="list">&lt;?php echo $toonmaand_04;?&gt;</a></li>
<li><a href="#" class="list">&lt;?php echo $toonmaand_05;?&gt;</a></li>
<li>&lt;?php echo "<a >Archief  (".$archief.")</a></li>";?&gt;
</ul>
</div>






This is just to much code for a simpel function but i have no idea or inspiration for a better construction.

Anyone have an idea?
#2

[eluser]n0xie[/eluser]
Wow that's a lot of redundant code :O

First off, why is there 5 functions in your model that do exactly the same thing?

You can replace all that with just one generic function 'count_month' where you give an 2 variables, the month, and the year.
Alternatively you could grab all 5 months in one go and just loop over them in the view.
Also you have written a function to translate the months to dutch. PHP can do this automagically for you so you don't have to think about it.

My proposal is:
Collect all the data in 1 array.
Then in your view, loop over the array and format them accordingly. You are now putting presentation (the way it looks) logic in your controller, which will be a pain if you ever want to change it.
#3

[eluser]Callista[/eluser]
[quote author="n0xie" date="1251295789"]Wow that's a lot of redundant code :O

First off, why is there 5 functions in your model that do exactly the same thing?

You can replace all that with just one generic function 'count_month' where you give an 2 variables, the month, and the year.
Alternatively you could grab all 5 months in one go and just loop over them in the view.
Also you have written a function to translate the months to dutch. PHP can do this automagically for you so you don't have to think about it.

My proposal is:
Collect all the data in 1 array.
Then in your view, loop over the array and format them accordingly. You are now putting presentation (the way it looks) logic in your controller, which will be a pain if you ever want to change it.[/quote]

First:
The months are in numbers in my database. That's why i had the translation code. To translate them from month numbers to month names. how would you let php do this automatically?

Second:
How do you get the last five months in one loop? because i had to calculate them moth by month i needed the model function month by month. If i can calculate them in one function i would be really glad but i couldn't get it done. Because i have to look at the years as well. That way if it's January 2010. The last 5 months are January 2010, December 2009, November 2009 etc. etc.


Maybe i just got to lost in all my codes but i have no clue how to make this smaller and i really want it smaller because like you said it looks like a lot of redundant code.
#4

[eluser]n0xie[/eluser]
[quote author="Callista" date="1251296570"]
First:
The months are in numbers in my database.
[/quote]
How do you store them in your table? As integers or as date? Take a look at the date() function in php. It will take an timestamp and format it any way you want.

Quote:Second:
How do you get the last five months in one loop? because i had to calculate them moth by month i needed the model function month by month. If i can calculate them in one function i would be really glad but i couldn't get it done. Because i have to look at the years as well. That way if it's January 2010. The last 5 months are January 2010, December 2009, November 2009 etc. etc.
This is a rather crude example but it will show you how to build an array for the last 5 months. How you fill that array is up to you.

Code:
function voorbeeldje()
    {
        for ($i = 1; $i <= 5; $i++)
        {
            $months[] = $this->get_previous_month('2009/09/26', $i);
        }
        print_r($months);
    }
    
    function get_previous_month($date, $months)
    {
        $date = str_replace("/", "-", $date);

        $year=date("Y",strtotime($date));
        
        $month=date("n",strtotime($date)) - $months;

        if ($month == 0) {
            $month = 12;
            $year = $year - 1;
        }
        return date("m", mktime(0, 0, 0, $month, 1, $year));
    }


As you can see, you can feed the function a MySQL date, which is easy to produce with the date() function.
#5

[eluser]Callista[/eluser]
yikes!

ok i'll have to study that code. I'm learning programming pretty fast but i'm still not that good in programming that i instantly understand codes haha

you asked about my database:
Right now i have 3 seperates fields in my nieuws_table for the days, months and years. This so i could select news on a month. These fields are simpel varchars. With the date function it produces a whole date (right?) not just a month. So i thought i couldn't use that.

But i'll take a look at the codes. I like your solution for the year problem with the if($month == 0).
#6

[eluser]jedd[/eluser]
You may want to read up on the MySQL (I'm assuming you're using this DB) reference manual at the options for date/time types. Rather than using 3 x columns for managing years, months, days - you could use something like the DATE type for just one column. If you want to keep the time of the posting (?) as well, you could look at DATETIME.

Happily lots of people have already come before you with these problems, so SQL and PHP have all kinds of functions for showing the difference between two dates, selecting X months ago (even when it spans new-year borders) and so on. Anyhoo, I suspect this would make your life much easier in the long term.
#7

[eluser]n0xie[/eluser]
Since you're new to programming I'll try to get you on your way. It could be written cleaner but hopefully you can follow the actions this way:

CONTROLLER
Code:
$today = date('Y/m/d');
$number_of_months = 5;

$this->load->model('test_model');
$data['lastmonths'] = $this->test_model->get_last_months($today,$number_of_months);

MODEL
Code:
function get_last_months($startdate = NULL, $number_of_months = 5)
    {
        if (is_null($startdate))
        {
            // if we supply no value we default to today
            $startdate = date('Y/m/d');
        }
        
        /**
         * create our array of months with an array key for the month,
         * array key for the year and another for the count
         */
        for ($i = 1; $i <= $number_of_months; $i++)
        {
            $prev = $this->get_previous_month($startdate, $i);
            $result[$i]['month'] = $prev['month'];
            $result[$i]['year']  = $prev['year'];
            $result[$i]['count'] = $this->count_month($prev['month'],$prev['year']);
        }
        return($result);
    }

    function count_month($month_number, $year)
    {
    
        $this->db->select('nieuws_datum_maand');
        $this->db->where("nieuws_status",1);
        $this->db->where("nieuws_datum_maand",$month_number);
        $this->db->where("nieuws_datum_jaar",$year);
        $this->db->from('nieuws');
        
        return $this->db->count_all_results();
    }
    
    function get_previous_month($date, $months)
    {
        $date = str_replace("/", "-", $date);

        $year=date("Y",strtotime($date));
        
        $month=date("n",strtotime($date)) - $months;

        if ($month == 0) {
            $month = 12;
            $year = $year - 1;
        }
        $dates['month'] = date("m", mktime(0, 0, 0, $month, 1, $year));
        $dates['year']  = date("Y", mktime(0, 0, 0, $month, 1, $year));
        return $dates;
    }

VIEW
Code:
<div class="nieuwslist">
<ul>
&lt;?php
        foreach($lastmonths as $item)
        {
            echo '<li><a href="#" class="list">'.date("F", mktime(0, 0, 0, $item['month'], 1, $item['year'])).' ('.$item['count'].')</a></li>';
        }
?&gt;
</ul>
</div>

If your locale is set correctly, PHP should translate the month names automatically for you. Hope this helps and I hope this was what you were looking for Smile
#8

[eluser]Callista[/eluser]
This is great!! thank you soo much!!

i'm hitting myself now that i didn't think of a solution like this.

Sometime i just over think codes and get a little lost haha.
I make it more complicated then necessary.




Theme © iAndrew 2016 - Forum software by © MyBB