Mysqli_real_escape_string无法识别链接
I am using mysqli_real_escape_string to clean my user input before inserting it into my database. I have used it before without trouble, but for some reason this time it is not recognizing my link identifier.
//Connect to mysql server
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$link) {
die('Failed to connect to server: ' . mysqli_error());
}
//Function to sanitize the values received from the form (prevents SQL injection)
function clean($str) {
$str = trim($str);
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
$rtstr = mysqli_real_escape_string($link, $str);
return $rtstr;
}
For some reason when I try to input information through this file, it gives me the error "Undefined variable: link" and then "mysqli_real_escape_string() expects parameter 1 to be mysqli" for every time it encounters this function.
I am very confused because everything seems to be correct, but I can't find a way around this error. Is there something I'm doing wrong here? Or is it something outside of this code causing the issue?
我在使用mysqli_real_escape_string清理用户输入,然后将其插入数据库。 我以前使用它没有遇到任何麻烦,但由于某种原因,这次它没有识别我的链接标识符。 p>
//连接到mysql服务器
$ link = mysqli_connect(DB_HOST) ,DB_USER,DB_PASSWORD,DB_DATABASE);
if(!$ link){
die('无法连接到服务器:'。mysqli_error());
}
//用于清理从中接收的值的函数 表单(防止SQL注入)
function clean($ str){
$ str = trim($ str);
if(get_magic_quotes_gpc()){
$ str = stripslashes($ str);
} \ n $ rtstr = mysqli_real_escape_string($ link,$ str);
返回$ rtstr;
}
code> pre>
出于某种原因,当我尝试通过此输入信息时 文件,它给出了错误“Undefined variable:link”,然后“mysqli_real_escape_string()希望参数1在每次遇到此函数时都是mysqli。” p>
我很困惑因为 一切似乎都是正确的,但我无法找到解决此错误的方法。 我有什么问题吗? 或者它是否在此代码之外导致问题? p>
div>
You call $link
in your function but it is not defined in your function.
You have to pass it as a parameter or define it in the function.
Then, you have to call your function.
//Connect to mysql server
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$link) {
die('Failed to connect to server: ' . mysqli_error());
}
//Function to sanitize the values received from the form (prevents SQL injection)
function clean($str,$link) {
$str = trim($str);
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
$rtstr = mysqli_real_escape_string($link, $str);
return $rtstr;
}
clean('test',$link);
Just declare global $link within your function.
function clean($str) {
/* Other code */
global $link; // Add this
$rtstr = mysqli_real_escape_string($link, $str);
return $rtstr;
}
Hope this helps.
Peace! xD