maestro416
maestro416

Reputation: 924

Functions not able to find variable?

I have the following variable $user_id being set by

    //Check if user is logged in
session_start();
   if (!isset ($_SESSION['user_id']))
{
    header("location:login.php");     
} 
 elseif(isset ($_SESSION['user_id']))
  {
$user_id = $_SESSION['user_id'];
  }

and then within the same function file I have the following:

function course_menu()
  {
      $sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
            $subscriptionResult = mysql_query($sqlSubscription);

                while ($rows = mysql_fetch_assoc($subscriptionResult))
                    {
                        $user_id = $rows['user_id'];
                        $course_id = $rows['course_id'];
                        $course_title = $rows['course_title'];

                              if ($data_id == $rows['course_id'])

                              {
                                  echo
                                  '<li>
                                      <a href="chapters.php?course_id=',$course_id,'&course_name=',$course_title,'" class="active">',$course_title,' </a>
                                          </li>';
                              }
                                  else
                                  {
                                      echo          
                                                  '<li><a href="chapters.php?course_id=',$course_id,'&course_name=',$course_title,'">',$course_title,' </a></li>';
                                  }
                    }
  }

The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?

I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.

My question is, how can I get the function to be able to use the variable $user_id?

EDIT

So I've started doing

$user_id = $_SESSION['user_id'];
global $conn;

$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
            $subscriptionResult = $conn->query($sqlSubscription);
            while ($rows = mysqli_fetch_assoc($subscriptionResult))
                {
                    $user_id = $rows['user_id'];
                    $course_id = $rows['course_id'];
                    $course_title = $rows['course_title'];

                          if ($data_id == $rows['course_id'])

                          {
                              echo
                              '<li>
                                  <a href="chapters.php?course_id=',$course_id,'&course_name=',$course_title,'" class="active">',$course_title,' </a>
                                      </li>';
                          }
                              else
                              {
                                  echo          
                                              '<li><a href="chapters.php?course_id=',$course_id,'&course_name=',$course_title,'">',$course_title,' </a></li>';
                              }
                }

which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)

function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);

 while ($daterows = mysqli_fetch_assoc($date))
                    {
                        $course_registered = $daterows['course_title'];
                        $date_time = $daterows['end_date'];
                        $calculate_remaining = ((strtotime("$date_time")) - time())/86400;
                        $round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
                       // Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
                         if($round_remaining > 1)
                             {
                                 $remaining = $course_registered." ".$round_remaining." "."Days Remaining";
                                 $subscriptionStatus = 2;
                                 echo '<p>',$remaining,'</p>';
                             }

                        elseif ($round_remaining == 1) 
                             {
                                 $remaining = $course_registered." ".$round_remaining." "."Day Remaining";
                                 $subscriptionStatus = 1;
                                 echo '<p>',$remaining,'</p>';
                             }

                        elseif ($round_remaining <= 0) 
                            {
                                  $remaining = $course_registered." "."Expired"." ".$date_time;
                                  $subscriptionStatus = 0;
                                   echo '<p>',$remaining,'</p>';
                            }


                    }

//Check for most recent viewed video
 $sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
 $videoResult = $conn->query($sqlVideo);
 if ($videoRows = mysqli_fetch_assoc($videoResult))
 {
     $last_video = $videoRows['last_video'];
     $videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
     if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
     {
     $chapter_id = $chapteridResult['chapter_id'];
     }

     $videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
     if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
     {
     $course_id = $courseResult['course_id'];
     }
 }


}

Upvotes: 0

Views: 79

Answers (2)

maestro416
maestro416

Reputation: 924

The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?

Upvotes: 1

The function course_menu() will not recognize your $user_id, Since it is outside its scope.

Make use of global keyword to solve this issue.

function course_menu()
  {
   global $user_id;
   // your remaining code .........

Upvotes: 2

Related Questions