Geoff McLennan
Geoff McLennan

Reputation: 448

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?

Upvotes: 0

Views: 184

Answers (2)

Indrasis Datta
Indrasis Datta

Reputation: 8618

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

Upvotes: 0

Nutshell
Nutshell

Reputation: 8537

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

Upvotes: 1

Related Questions