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条)

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解