dtczp02204 2016-03-17 17:34
浏览 51
已采纳

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?

  • 写回答

2条回答 默认 最新

  • dongyang4615 2016-03-17 17:36
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?