1

I'm following a tutorial written in 2007 and they have me create this function with this code.

If I don't create the function and just hardcode it in the the webpage it works.

Here is the code:

function getAllSubjects() {
    $query = "SELECT * 
              FROM subjects 
              ORDER BY position ASC";
    $subjectSet = mysql_query( $query, $connection);
    confirmQuery($subjectSet);
    return $subjectSet;
}

This is how I implement it in the web page:

$queryArray = getAllSubjects();

When I run the code I get an error stating:

Notice: Undefined variable: connection in "

complaining its from the getAllSubjects() function. I'm creating the $connection variable in a file I call prior to calling this code, shouldn't that be fine? I call them in this order:

require_once("includes/connection.php") 
require_once("includes/functions.php") 

3 Answers 3

2

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.

Your variable $connection is in the Global Scope. To access it include this inside your function:

function getAllSubjects(){
global $connection;
$query = "SELECT * 
        FROM subjects 
        ORDER BY position ASC";
$subjectSet = mysql_query( $query, $connection);
confirmQuery($subjectSet);
return $subjectSet;
}

NOTE: Check this link for a more detailed explanation http://php.net/manual/en/language.variables.scope.php

Sign up to request clarification or add additional context in comments.

Comments

1
function getAllSubjects(){
    global $connection;
    $query = "SELECT * 
            FROM subjects 
            ORDER BY position ASC";
    $subjectSet = mysql_query( $query, $connection);
    confirmQuery($subjectSet);
    return $subjectSet;
}

Comments

1

The problem is that $connection is outside the scope of getAllSubjects()

Try using the global keyword to include it in the scope of the function.

function getAllSubjects() {
    global $connection;
    //...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.