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.

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());
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.