problem with "real_escape_string"


problem with "real_escape_string"

我的"real_escape_string"遇到了一些问题,我需要的帮助

login.php

<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
    $sql = $mysqli->real_escape_string($sql);
    return $sql;
}
?>

local.php

<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
?>

错误是

Undefined variable: mysqli

我已经尝试了一些方法(比如在login.php中移动local.php的内容),但没有任何效果

您不能在函数中访问$mysqli。如果需要,请在函数中添加global $mysqli;以使其可访问。或者,您可以将$mysqli作为参数传递。

为什么不直接使用函数调用呢。

我的建议是,只需创建一个更简单(更易于阅读的函数),称为"esc",并在需要转义任何与sql相关的内容时使用它。

 function esc($string, $mysqli = false) {
    if (!$mysqli) global $mysqli;
    return mysqli_real_escape_string($mysqli,$string);
 }

然后只需执行以下操作即可使用:

 $sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function

 $sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call