HLB
HLB

Reputation: 558

Using a PHP function with a variable

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") 

Upvotes: 1

Views: 134

Answers (3)

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

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;
    //...

Upvotes: 1

Tivie
Tivie

Reputation: 18933

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

Upvotes: 2

user1744166
user1744166

Reputation:

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

Upvotes: 1

Related Questions