CodeIgniter Forums
Active Record Class output sql instead of executing - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Active Record Class output sql instead of executing (/showthread.php?tid=12166)



Active Record Class output sql instead of executing - El Forum - 10-08-2008

[eluser]newsun[/eluser]
I am wondering if there is a way to output sql from an active record call instead of executing it on the db?

During development I like visually verify that what I wrote is outputting the correct sql.


Active Record Class output sql instead of executing - El Forum - 10-09-2008

[eluser]frietkot[/eluser]
Just use the print_r() (or var_dump) function instead of echo or print.


Active Record Class output sql instead of executing - El Forum - 10-09-2008

[eluser]xwero[/eluser]
only the select statements can be shown using db->_compile_select(), the 'write' statements just pass the necessary parts to the driver method.

If you use the AR library it will always output valid sql but if it's the sql statement you wanted that is another question.


Active Record Class output sql instead of executing - El Forum - 10-09-2008

[eluser]newsun[/eluser]
Hmm ok, I might have to add that in as it's really handy for verification during development. If I do, I will post my changes so others can use as well.


Active Record Class output sql instead of executing - El Forum - 10-09-2008

[eluser]xwero[/eluser]
I just did a bit a checking and the methods _compile_select, _insert, _update, _truncate and _delete can be used to retrieve the sql statement but then all the parts of the sql statement have to be declared before the action method so instead of writing
Code:
$query = $this->db->get('table');
You have to write
Code:
$this->db->from('table');
$query = $this->db->get();
If you follow this rule you can use following helper
Code:
// helpers/db_debug.php
<?php
function show_select()
{
    $CI =& get_instance();
    return $CI->db->_compile_select();
}

function show_insert()
{
    $CI =& get_instance();
    return $CI->db->_insert();
}

function show_update()
{
    $CI =& get_instance();
    return $CI->db->_update();
}

function show_truncate()
{
    $CI =& get_instance();
    return $CI->db->_truncate();
}

function show_delete()
{
    $CI =& get_instance();
    return $CI->db->_delete();
}