Welcome Guest, Not a member yet? Register   Sign In
Problem passing arguments to function in codeigniter
#1

[eluser]Unknown[/eluser]
Hello fellow coders. I need help in figuring something out. I am using CodeIgniter framework. I created library called common_funtions. This library enables me to call a function in different controllers. One function in particular needs an argument. But I’m getting 3 errors when I call the function.

A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Common_functions::time_ago(), called in \...\get_comments.php on line 11 and defined
Filename: libraries/Common_functions.php
Line Number: 20

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: time
Filename: libraries/Common_functions.php
Line Number: 26

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: time
Filename: libraries/Common_functions.php
Line Number: 39

Here is my code:
In the library: common_functions.php

Code:
// The following function calculates ‘how long ago’
function time_ago($time)
{        
    $periods = array('second', 'minute', 'hour', 'day');
    $lengths = array('60', '60', '24', '7');
    $tense = 'ago';
    $now = time();
    $time_diff = $now - $time;
    for ($j = 0; $time_diff >= $lengths[$j] && $j < count($lengths)-1; $j++)
    {
        $time_diff /= $lengths[$j];
    }
    $time_diff = round($time_diff);
        if ($time_diff != 1)
    {
        $periods[$j].='s';
    }
    if ($time_diff > 7 && $periods[$j] == 'days')
    {
        $time_ago = date("l dS F, Y", $time);
    } else {
        $time_ago = $time_diff." ".$periods[$j]." ago";
    }
    return $time_ago;
}

In my controller:

Code:
$query = $this->db->query(“SELECT * FROM post_comments where p_id = ‘$id’ ORDER BY date ASC”);
$comments = $query->result_array();
foreach ($comments as $comment)
{
    $comment['date'] = $this->common_functions->time_ago($comment['date']);
}

Is there something wrong with my code? Or maybe it’s a bug in my framework?
This is not the first time I’m experiencing this.

Kind regards
Daryl Lukas.
#2

[eluser]InsiteFX[/eluser]
Please wrap your code in code tags so we can read it!
Code:
// Remove the space after code!
[code ]
// your code here
[/code ]

InsiteFX
#3

[eluser]Nick_MyShuitings[/eluser]
is $comment[‘date’] set when you call the function? cuz that is a very simple PHP error, not a framework error. You are calling a function that DEMANDS a parameter or else it will throw an error... and from the error reports you are not supplying the parameter.

So, start with a big fat var_dump inside that foreach and prove to yourself that EVERY TIME there is a set variable of $comment[date]... alternatively, use an if statement with an isset($comment['date']) and avoid calling the function if you don't have a date.
#4

[eluser]Unknown[/eluser]
thanx nick. I will try dat




Theme © iAndrew 2016 - Forum software by © MyBB