Pengun
Pengun

Reputation: 744

how to use a variable outside a function

i have this initialization file called init.php which I have declared a variable called $db for a mysqli connection. Below is my code.

<?php
    ob_start();
    session_start();

    define('DBHOST', '127.0.0.1');
    define('DBUSER', 'root');
    define('DBPASSWORD', '');
    define('DBNAME', 'mydb');

    $db = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);

    if ($db->connect_error) {
        header('Location: 404.php');
    }

    require_once 'functions/User.php';
    require_once 'functions/Sanitize.php';

As you can see I required User.php inside the function folder, and on the User.php file i have this code

<?php
    function login($idnumber, $username, $password) {
        $idnumber = sanitize($idnumber);
        $username = sanitize($username);
        $password = sanitize($password);

        $hashed_password = get_hashed_password($username);
    }

    function get_hashed_password($username) {
        $username = sanitize($username);

        $sql = "SELECT `password` FROM `users` WHERE `username` = ?";

        $stmt = $db->prepare($sql);

        if(!$stmt) {
            echo 'invalid sql statement';
        }

        die();
    }

On the get_hashed_password() function i used the variable $db but i got an error message saying

Notice: Undefined variable: db in D:\xampp\htdocs\sample\functions\User.php on line 15

Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\sample\functions\User.php on line 15

Can someone help me how can I used the variable $db in any of my functions? Thanks in advance!

Upvotes: 1

Views: 83

Answers (2)

Mario Radomanana
Mario Radomanana

Reputation: 1698

Call $db as global

function get_hashed_password($username) {
    global $db;
    //...
}

Upvotes: 3

Satish Sharma
Satish Sharma

Reputation: 9635

you can use $GLOBALS inside the function like this

$your_var = "something";
function abc()
{
    $your_var = $GLOBALS['your_var'];

}

UPDATE 2 :

function get_hashed_password($username) {
        $username = sanitize($username);

        $sql = "SELECT `password` FROM `users` WHERE `username` = ?";
 $db = $GLOBALS['db'];
        $stmt = $db->prepare($sql);

        if(!$stmt) {
            echo 'invalid sql statement';
        }

        die();
    }

Upvotes: 1

Related Questions