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!
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();
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;
}
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"
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.
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()?
Codeignitier offers some public methods for this purpose.
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()