Peter
Peter

Reputation: 2306

codeigniter active record, generate, but do not execute query

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!

Upvotes: 2

Views: 7336

Answers (5)

Sachem
Sachem

Reputation: 491

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()?

Upvotes: 0

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

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;
}

Upvotes: 6

Phil Sturgeon
Phil Sturgeon

Reputation: 30766

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"

Upvotes: 5

kevtrout
kevtrout

Reputation: 4984

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();

Upvotes: 3

Rystraum
Rystraum

Reputation: 2025

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.

Upvotes: 2

Related Questions