【问题标题】:mysqli connection not working inside function? [duplicate]mysqli连接在函数内部不起作用? [复制]
【发布时间】:2013-07-07 10:46:50
【问题描述】:

我在 php 函数中执行 mysql 查询时遇到了一些问题。我得到的错误是

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

有几个文件相互调用,所以我将尝试概述必要的信息。

访问的网址:

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());
}
?>

我已验证所调用的查询有效。我还通过使用该软件的不同页面查询数据库来验证连接信息(上面屏蔽)是否有效。

我假设我一定在某处错过了报价或括号,但我对它可能在哪里感到困惑。

【问题讨论】:

  • 可变范围肯定是有意义的。我不确定我是否正在尝试从非本地位置调用局部变量?我相信我只是在调用全局变量?除非有什么我错过了
  • 阅读链接的答案肯定是有意义的。
  • 查看php.net/manual/en/language.variables.scope.php 处的第二个框config.php 中的$link 是全局范围,但您正在函数中访问本地范围$link。要么需要将其添加为函数参数allServers($link),要么在你的函数中声明global $link。 @YourCommonSense 的链接清楚地描述了这一点。
  • 请将您的链接传递给函数。使用全局是非常糟糕的做法!

标签: php mysql function mysqli


【解决方案1】:

问题在于 PHP 变量范围。在第一次引用 $link 变量之前,在 allServers() 函数中添加这一行:

global $link;

在此处查看更多信息: http://php.net/manual/en/language.variables.scope.php

【讨论】:

    【解决方案2】:

    在我看来,使用全局变量并不是一个好的解决方案。您可能会在某些范围内意外覆盖 $link($link 是您可能用于其他目的的变量的常用名称)变量,从而导致很多混乱和难以调试。 只需将其作为函数参数传递 - 更简洁易读:

    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;
        }
    }
    

    说实话,更好的解决方案是使用一些通用类/函数来建立您的 mysql 连接,如下所示:

    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
    }
    

    【讨论】:

      【解决方案3】:

      使用全局变量

      function allServers(){
      
      global $link
      
      ...
      ...
      ...
      ... your code follows
      

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 2011-03-01
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多