使用数组发送查询参数

时间:2017-12-09 19:40:29

标签: php

我有一个类Pagination,其中包含一个计算文章总数的方法。当我实例化类时,我显式地键入sql查询并给他参数。这是一个例子:

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ?',
    'params' => "%$keyWord%"
]);

处理查询的方法运行它并返回结果:

return $this->db->getRows($this->query['query'], [$this->query['params']]);

但是,对于这个特殊情况(搜索文章),一切都很完美我想要的不仅是计算与标题匹配的结果,还要计算内容,换句话说我想要改为:

'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? OR content LIKE ?'

但是如何传递'params' => "%$keyWord%"中的第二个参数?

编辑: 分页课。

    public function __construct(string $table, $currentPage = 1, $perPage, $query = [])
{
    $this->db = Database::getInstance();
    $this->currentPage = $currentPage;
    $this->perPage = $perPage;
    $this->table = $table;
    $this->query = $query;

    $getTotalRows = $this->countResultsFromTable();
    $getTotalRows = $getTotalRows[0]->count;
    $this->total = ceil($getTotalRows / $this->perPage);
}

public function countResultsFromTable()
{
    if(empty($this->query))
    {
        return $this->db->getRows("SELECT COUNT(*) as count FROM $this->table");
    }
    else
    {
        return $this->db->getRows($this->query['query'], [$this->query['params']]);
    }
}

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:将通话​​延长至

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE ?',
    'title' => "%$keyWord%",
    'content' => $CONTENT
]);

和查询评估

return $this->db->getRows($this->query['query'],
  [$this->query['title'], $this->query['content']]
);

如果您不想更改Pagination类,请在实例化分页之前将内容附加到查询中:

$pagination = new Pagination(self::DATABASE_FORUM_TOPICS, $this->currentPage, self::TOPICS_IN_CATEGORY, [
    'query' => 'SELECT COUNT(*) as count FROM ' . self::DATABASE_FORUM_TOPICS . ' WHERE title LIKE ? AND content LIKE "%' . your_escaping_function($content) . '%"',
    'title' => "%$keyWord%"
]);