1

I have the following statement in my class and within a function. Now when wrap this around an if statement the

$this->setDayData(15, "test content = " .$list_day . "<br>");

doesn't work, but if i remove the if statement and just keep that in there it works fine. I've been breaking my head for the last few days on why this keeps happening and not working.

for($list_day = 1; $list_day <= $days_in_month; $list_day++){
            if($list_day == 15){
                $this->setDayData(15, "test content = " .$list_day . "<br>");   
            }
}

and i know that this check is working if($list_day == 15) because if i echo something in with in there it works. I can't understand why that if statement would cause $this->setDayData(15, "test content = " .$list_day . "<br>"); not to work.

Can anyone please help me with this?

FULL CLASS CODE

<?php
class Calendar{
    /**
     * holds the list of months
     * 
     * @var array
     * @access private
     */
    private $_months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

    /**
     * holds the list of days
     * 
     * @var array
     * @access private
     */
    private $_days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

    /**
     * holds all of the css class definitions
     * 
     * @var array
     * @access private
     */
    private $_class_defintions = array();

    /**
     * holds the month
     * 
     * @var integer
     * @access private
     */
    private $_month;

    /**
     * holds the year
     * 
     * @var integer
     * @access private
     */
    private $_year;

    /**
     * holds data that will be filled in each day
     * the indexes are zero-keyed
     * 
     * @var array
     * @access private
     */
    private $_day_data = array();

    /**
     * class constructor
     *
     * @param string|integer $month -- defines the month to be used in the calendar
     * @param integer $year -- defines the year
     * @param array $day_data -- zero-key index to define the data that will be displayed with each day
     * @access public
     * @return void
     */
    public function __construct($month = false, $year = false, array $day_data = array()){
        include "config/config.php";
        $this->setMonth($month)
            ->setYear($year)
            ->setMultipleDayData($day_data)
            ->setDefaultClassDefinitions();

            try {
                // Generate a database connection, using the PDO connector
                // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
                // Also important: We include the charset, as leaving it out seems to be a security issue:
                // @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
                // "Adding the charset to the DSN is very important for security reasons,
                // most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"
                $this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
            } catch (PDOException $e) {
                $this->errors[] = MESSAGE_DATABASE_ERROR . $e->getMessage();
            }
    }


    /**
     * Checks if database connection is opened. If not, then this method tries to open it.
     * @return bool Success status of the database connecting process
     */
    private function databaseConnection()
    {   
        include "config/config.php";
        // if connection already exists
        if ($this->db_connection != null) {
            return true;
        } else {
            try {
                // Generate a database connection, using the PDO connector
                // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
                // Also important: We include the charset, as leaving it out seems to be a security issue:
                // @see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Connecting_to_MySQL says:
                // "Adding the charset to the DSN is very important for security reasons,
                // most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!"
                $this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
                return true;
            } catch (PDOException $e) {
                $this->errors[] = MESSAGE_DATABASE_ERROR . $e->getMessage();
            }
        }
        // default return
        return false;
    }

    /**
     * Search into database for the days that have tasks and month is passed as a parameter
     * @return PDO query 
     * @return false if nothing is found for that month
     */
    private function getTaskDays($month)
    {
        // if database connection opened
        //if ($this->databaseConnection()) {
            // database query, getting all the info of the selected user
            $query_tasks = $this->db_connection->prepare('SELECT DAYOFMONTH(due_date) AS Day FROM tbl_tasks WHERE status = "active" AND MONTH(due_date) = :month');
            $query_tasks->bindValue(':month', $month, PDO::PARAM_STR);
            $query_tasks->execute();
            // get result row (as an object)
            return $query_tasks->fetchAll(PDO::FETCH_COLUMN, 0);
        //} else {
            return false;
        //}
    }

    /**
     * Converts array that is generated by PDO and converts into csv list
     * @return csv list
    */
    private function getListDays($month){
        $qry  = $this->getTaskDays($month);
        $list = implode(",", $qry);
        return $list;
    }


    /**
     * Checks to see if number(which should be current day is in list of tasks)
     * @return true
     * @return false if nothing is found
    */
    private function checkDay($day, $list){
        $dates = explode(',', $list);
        return in_array($day, $dates);      
    }



    /**
     * this method sets the css to be used in the calendar creation see {@link: $_class_definitions} for allowed keys
     *
     * @param array $settings
     * @access public
     * @return System_Utility_Calendar
     */
    public function setCssDefinitions(array $settings = array()){
        $this->_class_defintions = array_merge($this->_class_defintions, $settings);

        return $this;
    }

    /**
     * this method sets the month value
     * it will convert a sting-based value to an integer one    
     * if no month is passed in, it will use the current month
     *
     * @param string|integer $month -- defines the month to be used in the calendar
     * @access public
     * @return System_Utility_Calendar
     */
    public function setMonth($month = false){
        if(!(bool) $month){
            $month = date('n', time());
        }elseif(!is_int($month)){
            foreach($this->_months as $key => $name){
                if(preg_match('/^'. $month .'/i', $name)){
                    $month = $key + 1;

                    break;
                }
            }
        }

        $this->_month = $month;

        return $this;
    }

    /**
     * sets the year
     * if no year is passed it, it will use the current year
     *
     * @param integer $year
     * @access public
     * @return System_Utility_Calendar
     */
    public function setYear($year){
        if(!isset($year)){
            $year = date('Y', time());
        }

        $this->_year = $year;

        return $this;
    }

    /**
     * method used to assign how the days of the week will be displayed
     *
     * @param array $days
     * @access public
     * @return System_Utility_Calendar
     */
    public function setDaysOfWeek(array $days = array()){
        $this->_days = $days;

        return $this;
    }

    /**
     * sets the data for each day of the month
     * uses a zero key index
     *
     * @param array $data -- the key is the day (actual day minus one) the value is the data to be passed in that day
     * @param boolean $append -- this will say to overwrite the day or not with the data. Defaults to true
     * @access public
     * @return System_Utility_Calendar
     */
    public function setMultipleDayData(array $data = array(), $append = true){
        if(count($data)){
            foreach($data as $day => $content){ 
                $this->setDayData($day, $content, $append);
            }
        }

        return $this;
    }

    /**
     * sets the data for a given day
     *
     * @param integer $day -- the zero key of the day to be modified
     * @param mixed $content -- the content for that day
     * @param boolean $append -- this will say to overwrite the day or not with the data. Defaults to true
     * @access public
     * @return return type
     */
    public function setDayData($day, $content, $append = true){
        $current_content       = isset($this->_day_data[$day]) ? $this->_day_data[$day] : '';
        $this->_day_data[$day] = $append ? $current_content . $content : $content;

        return $this;
    }


    /**
     * this creates the calendar
     *
     * @access public
     * @return string
     */
    public function build(){
        $running_day       = date('w', mktime(0, 0, 0, $this->_month, 1, $this->_year));
        $days_in_month     = date('t', mktime(0, 0, 0, $this->_month, 1, $this->_year));
        $days_in_this_week = 1;
        $day_counter       = 0;
        $rows              = array();
        $row_count         = 6;
        $day_head          = $this->dayHead();
        $month_head        = $this->monthHead();
        $cells             = '';
        $listDays          = $this->getListDays($this->_month);


        /**
         * create the leading empty cells
         */
        for($x = 0; $x < $running_day; $x++){
            $cells .= $this->day(false);

            $days_in_this_week++;
        }

        /**
         * creates the rest of the days for the week
         * if it is the last day of the week, wrap the cells in a row
         */
        for($list_day = 1; $list_day <= $days_in_month; $list_day++){
            $cells .= $this->day($list_day);


            if($list_day == 15){

                echo "the day is 15 " . $list_day . "<br>";
                $this->setDayData(15, "test content = " .$list_day . "<br>");

            }


            if($running_day == 6){
                $rows[]            = $this->row($cells, $this->_class_defintions['row']);
                $cells             = '';
                $running_day       = -1;
                $days_in_this_week = 0;

                $row_count--;
            }

            $days_in_this_week++; 
            $running_day++; 
            $day_counter++;
        }


        /**
         * build the trailing empty days
         */
        if($days_in_this_week < 8){
            for($x = 1; $x <= (8 - $days_in_this_week); $x++){
                $cells .= $this->day(false);
            }

            $row_count--;
        }

        $rows[] = $this->row($cells, $this->_class_defintions['row']);

        /**
         * if there are still rows left, create an empty row
         */
        if($row_count > 0){
            $empty = '';

            for($x = 1; $x <= 7; $x++){
                $empty .= $this->day(false);
            }

            $rows[] = $this->row($empty, $this->_class_defintions['row']);
        }

        return $this->table($month_head . $day_head . implode('', $rows));
    }

    /**
     * resets the class so that the same instance can be used to create another month
     *
     * @access public
     * @return System_Utility_Calendar
     */
    public function reset(){
        $this->_month    = false;
        $this->_year     = false;
        $this->_day_data = array();

        return $this->setDefaultClassDefinitions();
    }

    /**
     * method used to create the outlining table
     *
     * @param string $content -- the rows and cells
     * @access private
     * @return string
     */
    private function table($content){
        return '
            <table cellpadding="0" cellspacing="0" class="'. $this->_class_defintions['calendar'] .'">
                <tbody>
                    '. $content .'
                </tbody>
            </table>
        ';
    }

    /**
     * method used to display the month heading
     *
     * @access private
     * @return string
     */
    private function monthHead(){
        return '
            <tr class="'. $this->_class_defintions['month_head'] .'">
                <td class="'. $this->_class_defintions['heading'] .'" colspan="7">'. $this->_months[($this->_month - 1)] .'</td>
            </tr>
        ';
    }

    /**
     * method used to create the day heading
     *
     * @access private
     * @return string
     */
    private function dayHead(){
        return '
            <tr class="'. $this->_class_defintions['row'] .'">
                <td class="'. $this->_class_defintions['heading'] .'">'. implode('</td><td class="'. $this->_class_defintions['heading'] .'">', $this->_days). '</td>
            </tr>
        ';
    }

    /**
     * this method will build out a day in the calendar
     * if false is passed in for the day, an empty day cell will be returned
     *
     * @param integer|booean $day -- the current day of the month that is being built
     * @access private
     * @return string
     */
    private function day($day){
        if((bool) $day){
            $class   = $this->_class_defintions['working_day'];
            $content = isset($this->_day_data[($day)]) ? $this->_day_data[($day)] : '';
            $day_num = '<div class="'. $this->_class_defintions['day_number'] .'">'. $day .'</div>';

            /**
             * if there is content, set the class to whatever is content_day
             */
            if($content !== ''){
                $class = $this->_class_defintions['content_day'];
            }
        }else{
            $class   = $this->_class_defintions['blank_day'];
            $content = '';
            $day_num = '';
        }

        return '
            <td class="'. $class. '">
                <div class="calendar_day_container">
                    '. $day_num . $content .'
                </div>
            </td>
        ';
    }

    /**
     * method creates a week row
     *
     * @param string $content -- the cells that will fill the row
     * @param string $class -- the class to be used on the row
     * @access private
     * @return string
     */
    private function row($content, $class = ''){
        return '
            <tr class="'. $class .'">
                '. $content .'
            </tr>
        ';
    }

    /**
     * method used to define the default class names
     *
     * @access private
     * @return System_Utility_Calendar
     */
    private function setDefaultClassDefinitions(){
        return $this->setCssDefinitions(array(
            'blank_day'   => 'calendar-day-np',
            'working_day' => 'calendar-day',
            'content_day' => 'calendar-day-content',
            'day_number'  => 'day-number',
            'month_head'  => 'month-head',
            'row'         => 'calendar-row',
            'heading'     => 'calendar-day-head',
            'calendar'    => 'calendar'  
        ));
    }
}
?>
Brad Hazelnut
  • 1,603
  • 5
  • 21
  • 33
  • Your error is in `setDayData()` and that's where you should be looking – John Conde Sep 17 '14 at 19:24
  • i will put the setDayData function in the code as well and i can't seem to find anything in there that an if statement would cause it not to work – Brad Hazelnut Sep 17 '14 at 19:25
  • Can you log the parameters given inside setDayData – Tom Erik Støwer Sep 17 '14 at 19:30
  • well the function should set some data to be displayed and then what that number hits, it should display the data. Now when i run the if test the echo statement will run but the function doesn't seem to or at least it doesn't seem to work. But if i remove the if statement it works fine – Brad Hazelnut Sep 17 '14 at 19:34
  • tom, when the if statement is there, when i echo out the $current_content, its blank, but when i remove the if the $current_content has value, how can you explain that. The value is the same in both instances – Brad Hazelnut Sep 17 '14 at 19:39
  • I just added the full class code – Brad Hazelnut Sep 17 '14 at 19:46

1 Answers1

1

Edited - with solution

As I said the problem was not function but logic in your class.

In build() method you have such part of code:

$cells .= $this->day($list_day);


if($list_day == 15){

    echo "the day is 15 " . $list_day . "<br>";
    $this->setDayData(15, "test content = " .$list_day . "<br>");

}

The problem is that you should change the order for those actions:

if($list_day == 15){

    echo "the day is 15 " . $list_day . "<br>";
    $this->setDayData(15, "test content = " .$list_day . "<br>");

}

$cells .= $this->day($list_day);

Now even if you use if everything is working fine as I said this has nothing in common with setDayData function because this function doesn't display anything.

Edited answer after adding full class code

There is no error in your code. Function setDayData is executed as it should. If you go to your function build and after finishing loop:

for($list_day = 1; $list_day <= $days_in_month; $list_day++){
 // rest of code
}

you add:

var_dump($this->_day_data);

you will get result:

array(1) { [15]=> string(21) "test content = 15
" } 

so as you see function is being executed and assign content to variable as it should.

Previous answer

There is no error in this code.

When I run the following code based on what you put in your question:

<?php


class Test
{

    public function foo()
    {
        $days_in_month = 100;
        for ($list_day = 1; $list_day <= $days_in_month; $list_day++) {
            if ($list_day == 15) {
                $this->setDayData(15, "test content = " . $list_day . "<br>");
            }
        }

        echo $this->_day_data[15];
    }


    public function setDayData($day, $content, $append = true)
    {

        $current_content = isset($this->_day_data[$day])
            ? $this->_day_data[$day] : '';
        $this->_day_data[$day] = $append ? $current_content . $content
            : $content;

        return $this;
    }

}


$x = new Test();

$x->foo();

output is:

test content = 15<br>

as expected.

You should definitely evaluate $days_in_month value because if it's less than 15 function of course won't be run. If it's value is more than 15, you should look for error in other part of your code.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • i see what you're saying and you're right it is being passed, but for some reason its not displaying anything though as it should and does when the if statement isn't there – Brad Hazelnut Sep 17 '14 at 20:43
  • @BradHazelnut Unfortunately that's not connected to the question you asked. You asked about function and it's working fine without any problems. – Marcin Nabiałek Sep 17 '14 at 21:43
  • yeah but the function is not working fine, because as soon as the if statement is there it doesn't display what its supposed to – Brad Hazelnut Sep 18 '14 at 13:00
  • @BradHazelnut Function `setDayData` according to your code is not supposed to display anything. It just sets class property value and that's it – Marcin Nabiałek Sep 18 '14 at 13:04
  • but you will notice that you if you take the if statement out, it will display the $content on that day of the calendar – Brad Hazelnut Sep 18 '14 at 14:57
  • @BradHazelnut But where do you see `echo` in this function? I see none. So something will be displayed but other functions will do it, not this one. Probably you have some errors in your logic in the class and SO is not for analysing big piece of code and finding logic errors in it. – Marcin Nabiałek Sep 18 '14 at 15:10
  • I completely understand that, im not asking to analyze all the code. And if there is a logic error i would definitely try to fix it. But this is where i am getting confused and asking for help. as to why an if statement would cause that function not display anything for that day, have you been able to test it just to see what i am talking about? – Brad Hazelnut Sep 18 '14 at 15:15
  • @BradHazelnut You have solution in my edited answer (at the beginning) – Marcin Nabiałek Sep 18 '14 at 15:27
  • you are the man, thnk you very much, i really appreciate your help. You were right it was in the logic, i guess i just couldn't find where it was messed up. But thank you very much – Brad Hazelnut Sep 18 '14 at 19:02
  • @BradHazelnut You should always try to analyse your code and if you have problem you should explain in details what doesn't work. You shouldn't tell that function doesn't display something if some other function displays something because it's really misleading and as you see I was the only person who tried to help you – Marcin Nabiałek Sep 18 '14 at 19:04
  • you're right and i thank you very much for that. and yes from now on i will definitely try to analyze my code better – Brad Hazelnut Sep 18 '14 at 19:13