使用php mysqli从两个连接表中获取数据

时间:2014-12-08 17:20:14

标签: php mysql sql mysqli

我有两个连接的表 - daysuser_days

DAYS: enter image description here

USER_DAYS: enter image description here

我如何使用user_id检查user_days中是否存在today(unix_date)记录,如果是,那么我需要在此之后获取day_id以从表DAYS获取数据,并将day_id作为ID ...

我写道:

 public function getDay($user_id) {
        $stmt = $this->conn->prepare("SELECT d.id, d.day, d.status, d.created_at, d.dayDate from days d, user_days ud WHERE d.id = ? AND ud.dayDate = d.dayDate AND ud.user_id = ?");
        $t=time();
        $dayDate = date("Y-m-d",$t);
        $stmt->bind_param("si", $dayDate, $user_id);
        if ($stmt->execute()) {
            $res = array();
            $stmt->bind_result($id, $day, $status, $created_at, $dayDate);
            // TODO
            // $task = $stmt->get_result()->fetch_assoc();
            $stmt->fetch();
            $res["id"] = $id;
            $res["task"] = $task;
            $res["status"] = $status;
            $res["created_at"] = $created_at;
            $res["dayDate"] = $dayDate;
            $stmt->close();
            return $res;
        } else {
            return NULL;
        }

}

另一方面作为index.php我的代码不太重要:

$app->get('/days', 'authenticate', function() {
            global $user_id;
            $response = array();
            $db = new DbHandler();

            // fetch task
            $result = $db->getDay($user_id);

            if ($result != NULL) {
                $response["error"] = false;
                $response["id"] = $result["id"];
                $response["day"] = $result["day"];
                $response["status"] = $result["status"];
                $response["createdAt"] = $result["created_at"];
                $response["dayDate"] = $result["dayDate"];
                echoRespnse(200, $response);
            } else {
                $response["error"] = true;
                $response["message"] = "The requested resource doesn't exists";
                echoRespnse(404, $response);
            }
        });

我只是得到了不正确的输出:

 Object {error: false, id: 0, day: null, status: 0, createdAt: null}

我的QUERY有什么问题,我觉得QUERY有问题,但我可以解决几个小时......

1 个答案:

答案 0 :(得分:2)

在getday()中,我认为您应该将$res["task"] = $task;替换为$res["day"]=$day