如何将变量声明为全局变量,以便可以在任何函数中使用。 我想要db connect变量 这是我的数据库连接代码 strong> p>
,这是我的功能 strong> p>
$ connect code>。 在我的函数中,$ connect变量不起作用,因为它们位于同一页面中。 p>
$ localhost =“localhost”;
$ username =“root”;
$ password =“”;
$ dbname =“xxxxxxxx”;
//创建连接
$ connect = new mysqli($ localhost,$ username,$ password,$ dbname);
//检查连接
if($ connect-> connect_error){
die(“连接失败:”。$ connect- > connect_error);
}
code> pre>
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;
}
code> pre>
< p>想像下面那样使用该函数来保护输入。 如果还有其他解决方案,请帮我解决这个问题。 p>
$ username = secureInput($ _ POST ['username']);
$ password = secureInput($ _ POST ['password']);
code> pre>
div>
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']);