Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli connection not working inside function? [duplicate]

I'm having some problems performing a mysql query inside a php function. The error I am getting is

Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16

There are several files calling each other so I will attempt to outline the necessary information.

URL Accessed:

localhost/serverList/api/rest.php?action=allServers

serverList/api/rest.php

<?php
include 'inc/restFunctions.php';

$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
    $action = $_GET['action'];
}
else{
    $action = 'false';
}


if(in_array($action,$possibleCalls)){
    switch ($action){
        case 'allServers':
            $return = allServers();
        break;
        case 'allEnvs':
            $return = allEnvs();
        break;
        case 'allTypes':
            $return = allTypes();
        break;
        case 'false':
            $return = falseReturn();
        break;
    }
}

serverList/api/inc/restFunctions.php

<?php
include ('inc/config.php');

function allServers(){
    $serverInfoQuery = "SELECT * FROM servers"
    $allServerResults = $link->query($serverInfoQuery);
    $json = array();
    while($row = $allServerResults->fetch_assoc()){
        $json[]['serverID'] = $row['serverID'];
        $json[]['environment'] = $row['environment'];
        $json[]['type'] = $row['type'];
        $json[]['serverIP'] = $row['serverIP'];
        $json[]['serverDescription'] = $row['serverDescription'];
        $json[]['serverCreatedBy'] = $row['serverCreatedBy'];
        $json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
        $json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
        $json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
    }
    $jsonResults = json_encode($json);
    return $jsonResults;
}
?>

serverList/api/inc/config.php

<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
    exit('Connect failed: '. mysqli_connect_error());
}
?>

I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.

I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.

like image 851
mhopkins321 Avatar asked Dec 21 '22 03:12

mhopkins321


2 Answers

The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:

global $link;

See more here: http://php.net/manual/en/language.variables.scope.php

like image 59
romka Avatar answered Dec 24 '22 02:12

romka


In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging. Just pass it as a function parameter - much cleaner and easier to read:

function AllServers($link) {
    $serverInfoQuery = "SELECT * FROM servers";
    $allServerResults = $link->query($serverInfoQuery);
    //More PHP code
}    

if(in_array($action,$possibleCalls)){
    switch ($action){
        case 'allServers':
            $return = allServers($link);
        break;
    }
}

To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:

class DB {

    private static $link = null;

    public static function getConnectionResource() {
        //In that way we "cache" our $link variable so that creating new connection 
        //for each function call won't be necessary
        if (self::$link === null) {
            //Define your connection parameter here
            self::$link = new mysqli($host, $user, $password, $database);
        }
        return self::$link;
    }
}

function getAllServers() {
    $link = DB::getConnectionResource();
    //Preform your query and return results
}
like image 35
Mikk Avatar answered Dec 24 '22 03:12

Mikk