0

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(); 
nhatimme
  • 383
  • 3
  • 19

3 Answers3

1

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); 
mega6382
  • 9,211
  • 17
  • 48
  • 69
  • The wierd thing is I'm loading my external database.php (require_once). Global does not help neither. – nhatimme Oct 23 '17 at 14:02
0

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) {
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • 2
    That is certainly not the best practice. Global variables are [not recommended](https://stackoverflow.com/questions/12445972/stop-using-global-in-php). – GrumpyCrouton Oct 23 '17 at 14:00
0

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!

nhatimme
  • 383
  • 3
  • 19