Mysqli_fetch_assoc不适用于某个函数

时间:2017-10-23 13:56:34

标签: php mysqli

如果我将我的代码放在一个函数中,它就不起作用了。如果我摆脱了它正确响应的功能。我做错了什么?

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(); 

3 个答案:

答案 0 :(得分:1)

这是因为函数无法访问$conn变量,您需要将$conn变量作为参数提供给函数:

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); 

答案 1 :(得分:0)

这是因为该功能无法访问$conn

最佳做法是将此$conn声明为全球。

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

另一种方法是将$conn作为函数参数传递:

function dayClosure($conn) {

答案 2 :(得分:0)

解决方案:

<?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); 

?>

我需要我的文件,并且确实已将$ conn变量发送到该函数。多谢你们!