Undeclared variable error

1

I'm having variable declination problem in my PHP function.

Error message:

  

Notice: Undefined variable: extra in path \ do \ file \ functions.php on line 58

The function:

function show_users($user_id=0){

if ($user_id > 0){
    $follow = array();
    $fsql = "SELECT user_id FROM following WHERE follower_id='$user_id'";
    $fresult = mysql_query($fsql);

    while($f = mysql_fetch_object($fresult)){
        //array_push($follow, $f->user_id);
        $follow[] = $f->user_id;
    }
    if (count($follow)){
        $id_string = implode(',', $follow);
        $extra =  " AND id IN ($id_string)";
    }else{
        return array();
    }
}
$users = array();
$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";
$result = mysql_query($sql);

while ($data = mysql_fetch_object($result)){
    $users[$data->id] = $data->username;
}
return $users;}

The Line in question is:

$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";

How to solve?

    
asked by anonymous 02.03.2014 / 21:15

1 answer

5

The problem seems to be that the variable is not declared in cases where the condition of one of if is false. Both of this if (count($follow)){ and this if ($user_id > 0){ , to fail a the variable is never declared.

So to solve this, you can declare the variable empty as a precaution. In case the code goes into the if and receive new value fine. But in case you do not enter the if, then do not spoil the query.

So test:

$extra = ''; // <= acrescento ao código
if ($user_id > 0){
    $follow = array();
    
02.03.2014 / 21:52