0

Hi,
I Have this php code:

<?php
//require('dbconnection.php');
$conn = mysqli_connect('localhost','root','','user_registration');

    if (mysqli_connect_errno()){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();

    }else{} ;


function getUsers() {
    //return require('online-users.txt');
    $getAllUsers = mysqli_query($conn,"SELECT * FROM login");

    if($getAllUsers === FALSE) { 
    die(mysqli_error()); // TODO: better error handling
    }
    while($rows=mysqli_fetch_array($getAllUsers)){

        echo $rows["firstname"];
    }
}
?>

And i am getting this errors:

Notice: Undefined variable: conn in ......\users.php on line 13

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ..../users.php on line 9

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in ....\users.php 13

Can someone please tell me Why i am getting this error , i also have varialve conn and this give undefined.

2
Contributors
1
Reply
12
Views
1 Year
Discussion Span
Last Post by cereal
0

Hi,

it happens because of the variable scope, $conn is defined outside the function, so or you pass it as parameter, or you set it as global, or you use an anonymous function. Example:

$getUsers = function() use($conn) {
    $getAllUsers = mysqli_query($conn,"SELECT * FROM login");

    if($getAllUsers === FALSE)
        return FALSE;

    return mysqli_fetch_all($getAllUsers);
};

print_r($getUsers());
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.