Mysqli_fetch_assoc不适用于函数[重复]

If I put my code in a function it does not work. If I get rid of the function it is responding correctly. What I'm doing wrong?

function dayClosure() {
$qClosure = 'SELECT * FROM timeRegistration WHERE department IN ("4")';
$rClosure = mysqli_query($conn, $qClosure);

    while($row = mysqli_fetch_assoc($rClosure)) {
        if ($row['status'] == '3' && $row['enddate'] == '23-10-2017') {
            $totalWorkedTime += $row['worktime'];
            return $totalWorkedTime;
        }
    }
}

echo dayClosure(); 
</div>

This is because the function cannot access $conn variable, You need to provide the $conn variable to the function as a parameter:

function dayClosure($conn) {
$qClosure = 'SELECT * FROM timeRegistration WHERE department IN ("4")';
$rClosure = mysqli_query($conn, $qClosure);

    while($row = mysqli_fetch_assoc($rClosure)) {
        if ($row['status'] == '3' && $row['enddate'] == '23-10-2017') {
            $totalWorkedTime += $row['worktime'];
            return $totalWorkedTime;
        }
    }
}

echo dayClosure($conn); 

It's because the function in unable to access $conn

The best practice is to declare this $conn as global.

global $conn;
$conn = mysqli_connect(......); 

Another way is to pass $conn as function parameter:

function dayClosure($conn) {

Solution:

<?php

require_once('config.php');

function dayClosure($conn) {
$qClosure = 'SELECT * FROM timeRegistration WHERE department IN ("4")';
$rClosure = mysqli_query($conn, $qClosure);

    while($row = mysqli_fetch_assoc($rClosure)) {
        if ($row['status'] == '3' && $row['enddate'] == '23-10-2017') {
            $totalWorkedTime += $row['worktime'];
            return $totalWorkedTime;
        }
    }
}

echo dayClosure($conn); 

?>

I required my file and did sent the $conn variable to the function. Thanks guys!