0

im writing a login procedure, but im stuck at the this error and can't come up with a solution to fix it.

error: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in the same goes for mysqli_query(). i already know that $connection is the problem because of other posts + the error asks for a msqli object.

i have a file where you where can call a funtion to open or close the db connection in includes/controller/dbcontroller.php. which contains the following code.

<?php

function openDBConnection(){
    //1. create database connection
    define("DB_SERVER","localhost");
    define("DB_USER","root");
    define("DB_PASS","");
    define("DB_NAME","IppaSpil");

    $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

    // test if connection occured

    if(mysqli_connect_errno()){
        echo "err: ".$connection;
        die("Database connection failed: ".
            mysqli_connect_error().
            "(" . mysqli_connect_errno . ")"
            );
    }
}   

function closeConnection(){ 
    //close database connection
    mysqli_close($connection);
}   
?>

Then i have a file logincontroller which handles the login request. this file is also located in includes/controller/LoginController.php. this contains the following code.

<?php require_once("../session.php");?>
<?php require_once("DatabaseController.php");?>
<?php require_once("../functions.php");?>
<?php require_once("../validation_functions.php");?>
<?php 
    openDBConnection();
    if (isset($_POST['login'])) {       
        $username = $_POST["username"];
        $password = $_POST["password"];     

        //validations
        $required_fields = array("username", "password");       
        validate_presences($required_fields);   

        if (empty($errors)){            
            $found_user = attempt_login($username, $password);

            if ($found_user) {
                // Succesa              
                redirect_to("profile_page.php");    
            } else {
                //Failure       
                $_SESSION["failedlogin"] = "Username or password is wrong.";
                echo"wrong pass";
                closeConnection();
                //redirect_to("login_page.php");
            }               
        } else{
            echo $errors;
            $_SESSION["errors"] = $errors;
            closeConnection();
            //redirect_to("login_page.php");                
        }
    }else{  
        //prob get request
        closeConnection();
        redirect_to("login_page.php");
    }
?>

The last file that is part of this procedure is a functions file. this file includes all kinds of functions. but 2 of them are important for my procedure. the file is located in includes/functions.php. and this is the code. i get 2 errors in this file. the line where it gives the error are marked with a ||.

    function attempt_login($username, $password) {
    $admin = find_user_by_username($username);
    if ($admin) {
        // found admin, now check password

        if (password_check($password, $admin["password"])) {

            // password matches
            return $admin;
        } else {
            // password does not match

            return false;
        }
    } else {
        // admin not found
        return false;
    }
}

function find_user_by_username($username) {
global $connection;

$safe_username = mysqli_real_escape_string($connection, $username); ||

$query  = "SELECT * ";
$query .= "FROM user ";
$query .= "WHERE username = '{$username}' ";
$query .= "LIMIT 1;";

$user_query = mysqli_query($connection, $query); ||

confirm_query($user_query);
if($user = mysqli_fetch_assoc($user_query)) {       

    return $user;           
} else {

    return null;
}
}

i suspect that the global $connection variable cant be accessed, but i dont know why...

Thank you in advance!

Diceble
  • 733
  • 1
  • 7
  • 27

1 Answers1

1

The problem is that $connection is defined in the scope of the function openDBconnection().

Even though you try to access it with

global $connection

this doesn't work.

a little test:

<?php

function test() {
    $a = "test";
    return $a;
}

test(); // run it, but don't take the return
//$a = test();

function test2() {
   global $a;
   echo $a;   // doesn't show anything - $a is NULL
}

test2();

?>

If I uncomment //$a = test(); I get a result, because now $a is in global scope.

So you got the possibility to return $connection at the end of the function openDBconnection() and then assign it to a global in your script:

 // end of openDBconnection
return $connection;

// where you establish connection in your script:
$connection = openDBconnection();

BUT it's not good practice to use globals. It would be better to pass that connection to your functions:

function attempt_login($username, $password, $connection) {
    $admin = find_user_by_username($username, $connection);
    ....
}

function find_user_by_username($username, $connection) {
    ....
}
Jeff
  • 6,895
  • 1
  • 15
  • 33
  • I'm right by saying that if you want a global always defined, you'd need to store it in the `$_GLOBALS` variable yes? Just create a function called glob and set a global variable. :) – Jack Hales Dec 17 '16 at 23:43
  • @Jek Yes. But it always good to get used to avoid globals. Controlable in a small project, but once you include plugins or write them, .. With globals it's always easy to incidently overwrite something without even noticing. – Jeff Dec 17 '16 at 23:48
  • 1
    Thanks! I already suspected it was out of scope. Stupid by me, that I didnt recognized how to fix it... thanks for taking the time and giving a clear example of my mistake!:) – Diceble Dec 17 '16 at 23:49
  • Yeah agreed @Jeff, I'd never use globals to throw megabytes of data through each other, I currently don't see the need for the `GLOBAL` variable to have write perms from the main scope, but still! – Jack Hales Dec 17 '16 at 23:50
  • Also @BasvanUggelen don't serialize your connections `:)` – Jack Hales Dec 17 '16 at 23:51