codeigniter active record, generate, but do not execute query

余生颓废 提交于 2019-12-10 10:47:08

问题


I am working a library that needs to be fed sql queries as strings todo its job.

I am using CodeIgniter and the active record implementation of their database class.

I know that I can echo the SQL statement like so... But I only want to generate this query, not execute it.

 echo $this->db->last_query();

Any help accomplishing this would be great!


回答1:


The last_query() function you are using returns the query string, it doesn't execute the it. Try assigning the function return to a variable for use in your library.

$str = $this->db->last_query();



回答2:


with a little hack you can do it go to system/DB_active_rec.php and remove protected keyword form _compile_select method and now

return $this->db->_compile_select();

Also use $this->db->from('table');

Instead of get() because get will execute query Here is an example

function index(){
    $this->db->select('blah blah');
    $this->db->from('table');
    $string = $this->db->_compile_select();
    return $string;
}



回答3:


Depends which type of query it is. insert and update have methods to allow you to do this.

$this->db->set('foo', $bar);
$this->db->update_string('table'); // UPDATE table SET foo = "bar"



回答4:


I don't know if this is a safe practice but the db object stores its queries in the queries attribute so you can get it via:

$this->db->queries

which returns an array of queries.




回答5:


As of Codeigniter 3 you can use get_compiled_select()

To use it before CI3, see Is there a function like _compile_select or get_compiled_select()?




回答6:


Codeignitier offers some public methods for display query BEFORE execution :

Get a SELECT query

$sql = $this->db->get_compiled_select()

Get a INSERT query

$sql = $this->db->get_compiled_insert()

Get a UPDATE query

$sql = $this->db->get_compiled_update()

Get a DELETE query

$sql = $this->db->get_compiled_delete()


来源:https://stackoverflow.com/questions/5113675/codeigniter-active-record-generate-but-do-not-execute-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!