這是選擇從我使用好長一段時間的數據庫數據的基本方法..
/**
* Le wild function to make a life better.
* Doing abrakadabra
*
* @param $table
* @param bool $selector
* @param string $order
* @param bool $start
* @param bool $limit
* @param $return
*
* @return mixed
*/
public function _getCustomTableData($table, $selector = FALSE, $order = 'id DESC', $start = FALSE, $limit = FALSE, $return = FALSE, $group_by = FALSE)
{
$query = $return ? $this->db->select($return) : $this->db->select('*');
if ($selector) {
if (isset($selector['mixed_selection']) && $selector['mixed_selection'] == TRUE) {
$query = $this->db->where($selector['mixed_selection']);
} else {
foreach ($selector as $select_array):
$query = $this->db->where($select_array);
endforeach;
}
}
if ($group_by) {
$query = $this->db->group_by($group_by);
}
$query = $this->db->order_by($order);
if ($start && $limit) {
$query = $this->db->limit($limit, $start);
}
if (! $start && $limit) {
$query = $this->db->limit($limit);
}
// proceed
$query = $this->db->get($table);
if ($limit == TRUE && $limit == 1) {
$query = $query->row_array();
if ($return) {
return $query[$return];
} else {
return $query;
}
} else {
$query = $query->result_array();
return $query;
}
}
和查詢的樣子:
$this->_getCustomTableData('table', array(array('selector' => '1', 'time >=' => time())), 'id DESC', FALSE, 1, 'id');
它像:
SELECT 'id' FROM `table` WHERE `selector` = 1 AND `time` >= 1472582... ORDER BY id DESC LIMIT 1
或者您可以使用「混合自選ection「
$this->_getCustomTableData('table', array('mixed_selection' => 'selector = 1 AND time >= 1472582...'), 'id DESC', FALSE, 1, 'id');
並且結果將是相同的。我已經寫了這種方法,當我初學CI,它幫了我很多:)
你確定你的查詢產生'WHERE name = 1'? '$ data ['where'] ['and']';和'$ data ['where'] ['或']'包含了什麼? – 2015-03-19 13:27:17