函数将所有值返回为null,即使它们不是

时间:2019-07-25 17:28:45

标签: php arrays mysqli

该功能应该从我的数据库表中获取信息,将其添加到数组中并向我显示(我现在正在使用Postman进行测试)

但是,由于不明的原因,至少不对我来说,它们都没有返回正常值,而是全部设置为null。

DbOperations.php

function getPersonChanges_made($login_token){
    $stmt = $this->con->prepare("SELECT id, first_name, last_name, login_token, time_started, time_ended, todays_worktime FROM changes_made WHERE login_token = ? ");
    $stmt->bind_param("s", $login_token);
    $stmt->execute();
    $arrs = array(); 

    while($row = $stmt->fetch()) {
        $arr  = array();
        $arr['id'] = $row['id'];
        $arr['first_name'] = $row['first_name'];
        $arr['last_name'] = $row['last_name'];
        $arr['login_token'] = $row['login_token'];
        $arr['time_started'] = $row['time_started'];
        $arr['time_ended'] = $row['time_ended'];
        $arr['todays_worktime'] = $row['todays_worktime'];

        array_push($arrs, $arr);
    }

    return $arrs;  
}

Api.php

case 'getpersonchanges_made':
    isTheseParametersAvailable(array('login_token'));
    $db = new DbOperation();
    $result = $db->getPersonChanges_made($_POST['login_token']);

    if($result){
        $response['error'] = false; 
        $response['message'] = 'success';
        $response['arrs'] = $result;
    }else{
        $response['error'] = true; 
        $response['message'] = 'Some error occurred please try again';
    }
    break;

这是我得到的结果:

  

“ id”:null,“ first_name”:null,“ last_name”:null,“ login_token”:null,“ time_started”:null,“ time_ended”:null,“ todays_worktime”:null

1 个答案:

答案 0 :(得分:4)

fetch()返回一个布尔值。您可能正在寻找fetch_assoc(),但是不能直接在语句上调用它,只能在结果对象上调用它。例如:

$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {

还有另一个可用选项,可能更简单。

foreach($stmt->get_result() as $row) {

更新 正如@NigelRen所说,您还可以直接返回fetch_all()的结果,因为您在循环中所做的只是从一个数组移到另一个数组而无需进行任何更改。您的功能将变得更加简洁明了:

function getPersonChanges_made($login_token) {
    $stmt = $this->con->prepare("SELECT id, first_name, last_name, login_token, time_started, time_ended, todays_worktime FROM changes_made WHERE login_token = ? ");
    $stmt->bind_param("s", $login_token);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(\MYSQLI_ASSOC);
}