user3522457
user3522457

Reputation: 2963

check array is empty doesn't work using cast?

$stmt = $db->prepare("SELECT * FROM task where uId = ?");

$stmt->bind_param('s',$userId);

if($stmt->execute()){
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         $task[] = $obj;
    }

    if(count((array)$task)){
        $main[0]->tasks = $task;
    }
}

line $main[0]->tasks = $task; shows an error of Undefined variable: task. In my case there is no task in my record so the execution failed. But I expect it just skip and continue because I already put it within the 'if', which check whether the task object is empty.

Upvotes: 0

Views: 41

Answers (1)

user3470953
user3470953

Reputation: 11355

do something like

if($stmt->execute()){
    $task = array();
    $user = $stmt->get_result();
    while ($obj = $user->fetch_object()) {
         $task[] = $obj;
    }

    if(count($task)){ //or if($task){
        $main[0]->tasks = $task;
    }
}

Upvotes: 2

Related Questions