Undeclared variable error

Asked

Viewed 412 times

1

I have variable declension problem in my PHP function.

Error message:

Notice: Undefined variable: extra in path 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?

  • remove $extra... or declare it with some value....

1 answer

5


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

So to solve this can declare the variable, empty, as a precaution. In case the code enters the if and receives new value all right. But in case of not entering the if, then no longer spoils the query.

So test:

$extra = ''; // <= acrescento ao código
if ($user_id > 0){
    $follow = array();
  • What’s the most efficient way? That’s if you can...

  • @Marcelloinfoweb, I think that here does not make much difference in terms of efficiency. If you want you can also put in the else of if ($user_id > 0){

Browser other questions tagged

You are not signed in. Login or sign up in order to post.