Thực hiện nhiều câu truy vấn cùng một lần trong CodeIgniter (Excute multiquery with CodeIgniter)

Ngày 20 tháng 4 năm 2012 Trương Chương Dương
Trong một số trường hợp, để tối ưu hoá tốc độ thực hiện các câu truy vấn, hoặc để thực hiện một nhóm phức tạp các câu truy vấn khác nhau nhưng có liên quan tới nhau nên ta có thể nhóm một loạt các câu truy vấn và thực thi trong 1 lần execute duy nhất. Tuy nhiên mặc định CodeIgniter không hỗ trợ thực thi multi sql trong 1 lần gọi truy vấn, ví dụ đoạn sau sẽ bị báo lỗi:

$this->db->query("

update `table` set `value` = 1 where id = 123;

update `table` set `value` = 2 where id = 234;

update `table` set `value` = 3 where id = 456;

");
Hiện tại mình đang sử dụng CodeIgniter 3.0 tuy nhiên vẫn chưa thấy có dấu hiện nào là CodeIgniter sẽ hỗ trợ tính năng này. Tuy nhiên, bản thân DB driver mà CodeIgniter đang sử dụng đã hỗ trợ sẵn, chúng ta chỉ cần chỉnh một vài dòng code là có thể khiến cho CodeIgniter sẵn sàng để thực hiện nhóm các lệnh sql chỉ trong một lần execute. Cụ thể ta làm như sau:
  1. Tìm mở file system\database\drivers\mysqli\mysqli_driver.php
  2. Tìm function _execute, thay đoạn code function này bằng đoạn sau
/**
	 * Execute the query
	 *
	 * @param	string	an SQL query
	 * @return	mixed
	 */
	protected function _execute($sql)
	{
		$sql = $this->_prep_query($sql);
        $result = NULL;

        /* execute multi query */
        if (@mysqli_multi_query($this->conn_id, $sql))
        {
            do
            {
                if ($result)
                    @mysqli_free_result($result);
                
                $result = @mysqli_store_result($this->conn_id);
            }
            while (mysqli_next_result($this->conn_id));
        }
        
        if ($result === FALSE)
            $result = 1;

        /* close connection */
        return $result;//Only return last result

        /*
          $result = @mysqli_query($this->conn_id, $sql);
         * 
         */

        //return $result; 
	}

Lưu ý: Nếu bạn sử dụng CodeIgniter phiên bản mới, sử dụng object MySQLi thay vì dùng function truyền thống, thì đoạn code sẽ là:
/**
	 * Execute the query
	 *
	 * @param	string	an SQL query
	 * @return	mixed
	 */
	protected function _execute($sql)
	{

		$sql = $this->_prep_query($sql);
        $result = NULL;

        /* execute multi query */
        if (@$this->conn_id->multi_query($sql))
        {
            do
            {
                if ($result)
                    @$result->free();
                
                $result = $this->conn_id->store_result();
            }
            while ($this->conn_id->next_result());
        }
        
        if ($result === FALSE)
            $result = 1;

        /* close connection */
        return $result;//Only return last result

        /*
         return @$this->conn_id->query($this->_prep_query($sql));
         */
	}
Đang tải dữ liệu...