duanjipiao7076 2017-01-09 22:45
浏览 49
已采纳

PHP OOP查询返回空白或数组

New to OOP.

Trying to query the database for a specific row. Database is structured as: id - title - value

(I am trying to query match title and get the subsequent value)

The query either results in Array or is simply blank.

Certain my formatting is mixed up or incorrect somewhere. Can anyone spot what I'm doing wrong?

Query (which inside the same model where this is being called from) catalog/model/order.php:

public function getTemplate($title) {
    $query = $this->db->query("SELECT * FROM km_mail_templates WHERE `title` = '" . $this->db->escape($title) . "'");

    foreach ($query->rows as $result) {
            $template_data[$result['title']] = $result['value'];
    }

    return $template_data;
}

Variables I am trying to call:

public function index() {//called from within order.php model
  $this->getTemplate()['new_greeting'];
}

Also tried:

$this->model_catalog_order->getTemplate()['new_greeting'];

and

$this->model_catalog_order->getTemplate('new_greeting');
  • 写回答

1条回答 默认 最新

  • duan1982453 2017-01-09 22:58
    关注

    If the query doesn't find anything, the foreach() body will never be executed, so you'll never initialize $template_data, and you'll return null. You need to initialize it to an array before the loop.

    And since you're just overwriting the same array element each time through the loop, there's no point in looping, just get the one element from the array.

    There doesn't seem to be any need to return an array, you can just return the value that was retrieved by the query as a string.

    public function getTemplate($title) {
        $query = $this->db->query("SELECT * FROM km_mail_templates WHERE `title` = '" . $this->db->escape($title) . "'");
    
        if (!empty($query->rows)) {
            return $query->rows['value'];
        } else {
            return '';
        }
    }
    

    Then you would use it like this:

    $greeting = $this->getTemplate('new_greeting');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?