duandi6531
duandi6531
2017-02-24 14:41
浏览 48
已采纳

如何将变量声明为全局变量,以便可以在任何函数中使用

How to declare a variable as global variable so it can be use inside any function. I want the db connect variable $connect. In my function the $connect variable is not working as they are in the same page.

Here is my db connect code

$localhost = "localhost";
$username = "root";
$password = "";
$dbname = "xxxxxxxx";

// create connection
$connect = new mysqli($localhost, $username, $password, $dbname);

// check connection
if($connect->connect_error) {
    die("connection failed : " . $connect->connect_error);
}

and here is my Function

function secureInput($var){
    global $connect;
    $output = '';
    if (is_array($var)){
        foreach($var as $key=>$val){
            $output[$key] = secureInput($val);
        }
    } else {
        $var = strip_tags(trim($var));
        if (function_exists("get_magic_quotes_gpc")) {
            $output = mysqli_real_escape_string($connect,get_magic_quotes_gpc() ? stripslashes($var) : $var);
        } else {
            $output = mysqli_real_escape_string($connect,$var);
        }
    }
    if (!empty($output))
    return $output;
}

want to use that function as like bellow to secure input. If there is any other solution please help me to fix this.

$username = secureInput($_POST['username']);
$password = secureInput($_POST['password']);

图片转代码服务由CSDN问答提供 功能建议

如何将变量声明为全局变量,以便可以在任何函数中使用。 我想要db connect变量 $ connect 。 在我的函数中,$ connect变量不起作用,因为它们位于同一页面中。

这是我的数据库连接代码

  $ localhost =“localhost”; 
 $ username =“root”; 
 $ password =“”; 
 $ dbname =“xxxxxxxx”; 
 
 //创建连接
 $  connect = new mysqli($ localhost,$ username,$ password,$ dbname); 
 
 //检查连接
if($ connect-> connect_error){
 die(“连接失败:”。$ connect-  > connect_error); 
} 
   
 
 

,这是我的功能

  function secureInput($ var){
 global $ connect; 
 $ output =''; 
 if(is_array($ var)){
 foreach($ var as $ key => $ val){\  n $ output [$ key] = secureInput($ val); 
} 
} else {
 $ var = strip_tags(trim($ var)); 
 if(function_exists(“get_magic_quotes_gpc”)){
  $ output = mysqli_real_escape_string($ connect,get_magic_quotes_gpc()?stripslashes($ var):$ var); 
} else {
 $ output = mysqli_  real_escape_string($ connect,$ var); 
} 
} 
 if(!empty($ output))
 return $ output; 
} 
   
 
 <  p>想像下面那样使用该函数来保护输入。 如果还有其他解决方案,请帮我解决这个问题。   
 
 
  $ username = secureInput($ _ POST ['username']); 
 $ password = secureInput($ _ POST ['password']); 
    
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshang4984
    dongshang4984 2017-02-24 14:47
    已采纳

    Declaration:

    $GLOBALS['varName'] = "varContent";
    

    Usage:

    echo $GLOBALS['varName'];
    
    点赞 评论

相关推荐