为什么我无法在这里尝试获取非对象错误的属性?

时间:2019-04-06 23:29:17

标签: php pdo

我用PHP制作了MVC格式,但由于例行对象为null(您看到它为假),因此出现Trying to get property of non-object错误。简而言之,这里发生的是我得到了一个具有event_id的$ event对象,我正在寻找与event对象具有相同的例程ID的例程对象,但是我遇到了这个错误:

  

无注意:试图获取G:\ 5th中非对象的属性   第13行上的学期\电子商务\ xampp \ htdocs \ app \ controllers \ Event.php   bool(false)aaaaaaaaaaaaaaaaaaaaaarray(1){[0] => object(Event_model)#6   (8){[“ name”] => NULL [“ user_id”] => NULL [“ routine_id”] =>字符串(2)   “ 20” [“ year”] =>字符串(4)“ 2019” [“ month”] =>字符串(1)“ 3” [“ day”] =>   string(2)“ 27” [“ event_id”] => string(1)“ 3”   [“ _connection”:protected] => object(PDO)#7(0){}}}

我尝试var_dump $ routine和$ event,以便$ event显示例程ID,但$ routine为null。

测试代码:

var_dump($routine);
echo "aaaaaaaaaaaaaaaaaa";
var_dump($event);

public function index($y, $m, $d) {
    $event = $this->model('Event_model');
    $event = $event->getEventsbydate($y, $m, $d);

    $routine = $this->model('Routine_model'); 
    $routine = $routine->getRoutine($event->routine_id);

    if($event == false){ //if there is nothing in the workout_list

        header("location:/Event/create/$y/$m/$d"); //mylist controller , create method
    } else {
        var_dump($routine);
        echo "aaaaaaaaaaaaaaaaaa";
    var_dump($event);

        //header('location:/Routine/index_bycalendar/$event->routine_id'); 
    }
}

<?php
//for event
public function insert() {
$stmt = $this
    ->_connection
    ->prepare("INSERT INTO event(routine_id, year, month, day) VALUES(:routine_id, :year, :month, :day)");
$stmt->execute(['routine_id' => $this->routine_id, 'year' => $this->year, 'month' => $this->month, 'day' => $this->day]);
return $stmt->rowCount();
}

public function getEventsbydate($year, $month, $day) {
    $stmt = $this
        ->_connection
        ->prepare("SELECT * FROM event WHERE year = :year AND month = :month AND day = :day");
    $stmt->execute(['year' => $year, 'month' => $month, 'day' => $day]);
    $stmt->setFetchMode(PDO::FETCH_CLASS, "Event_model"); //datatype user
    return $stmt->fetchAll();
}

public function getRoutine($routine_id) {
    $stmt = $this
        ->_connection
        ->prepare("SELECT * FROM routine WHERE routine_id = :routine_id");
    $stmt->execute(['routine_id' => $routine_id]);
    $stmt->setFetchMode(PDO::FETCH_CLASS, "Routine_model"); //datatype user
    return $stmt->fetch(); //it should return a user
}

1 个答案:

答案 0 :(得分:0)

致电时...

$event = $event->getEventsbydate($y, $m, $d);

这应该运行SQL,然后返回...

return $stmt->fetchAll();

然后您在{p>中使用$event

$routine = $routine->getRoutine($event->routine_id);

但是fetchAll()返回一个事件数组,因此,如果您只期望一个事件,那么您可以选择其中一个...

return $stmt->fetch();

使用fetch()仅返回一行,或者

$routine = $routine->getRoutine($event[0]->routine_id);

因此,使用$event[0]选择第一行。

可能会有多个事件,在这种情况下,您可能需要循环并创建多个Routine_model