mysqli_real_escape_string() expects parameter 1 to be mysqli; mysql_result() expects parameter 1 to be resource

StackOverflow https://stackoverflow.com/questions/18887812

Question

I'm getting these errors:

Notice: Undefined variable: link in login.php on line 11

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in login.php on line 11

Notice: Undefined variable: link in login.php on line 18

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in login.php on line 18

Warning: mysql_result() expects parameter 1 to be resource, null given in login.php on line 19

Here's the code:

<?php

session_start();


$link = mysqli_connect('localhost','root','') or die(); 
mysqli_select_db($link,'lr') or die();  


function sanitize($data) {
    return mysqli_real_escape_string($link, $data);     <<line 11
}



function user_exists($username) {
    $username = sanitize($username);    
    $query = mysqli_query($link, "SELECT COUNT('user_id') FROM 'users' WHERE 'username' = '$username'");        <<line 18
    return (mysql_result($query, 0) ==1) ? true : false;        <<line19

}


if (empty($_POST) === false) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username) === true || empty($password) === true) {
        $errors[] = 'You need to enter a username and password';    

    } else if (user_exists($username) === false) {  
        $errors[] = 'User not found';
        }


}

?>

What's the problem?

Was it helpful?

Solution

You need to use $_GLOBALS['link'] inside function.

Like this:

    function sanitize($data) {
    return mysqli_real_escape_string($_GLOBALS['$link'], $data);     <<line 11
}

Same thing inside user_exist function.

OTHER TIPS

Global may have worked to fix the problem, but it's better to pass the variable into the function.

function sanitize($data, $A) {
    return mysqli_real_escape_string($A, $data);     <<line 11
}
function user_exists($username, $A) {
    $username = sanitize($username);    
    $query = mysqli_query($A, "SELECT COUNT('user_id') FROM 'users' WHERE 'usernam' = '$username'");        <<line 18
    return (mysql_result($query, 0) ==1) ? true : false;        <<line19

}

if (empty($_POST) === false) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if (empty($username, $link) === true || empty($password) === true) {
        $errors[] = 'You need to enter a username and password';    

    } else if (user_exists($username, $link) === false) {  
        $errors[] = 'User not found';
        }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top