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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制