简体   繁体   中英

Mysqli_real_escape_string not recognizing link

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM