2

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!

Peter
  • 2,276
  • 4
  • 32
  • 40

5 Answers5

6

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;
}
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
5

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"
Phil Sturgeon
  • 30,637
  • 12
  • 78
  • 117
3

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();
kevtrout
  • 4,934
  • 6
  • 33
  • 33
2

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.

Rystraum
  • 1,985
  • 1
  • 20
  • 32
0

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

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Sachem
  • 481
  • 1
  • 4
  • 13