Echo query before execution and without execution

2019-03-09 19:28发布

问题:

I am looking for a way to see generated string of the query but without executing it.

Note that the query hasn't been executed before. (I do not want $this->db->last_query();)

I hope there be a method with a name like $this->db->echo_query_string($table_name = ''); to be used exactly like $this->db->get($table_name = ''); BUT THE ONLY DIFFERENCE BE THAT get() executes the code, but echo_query_string() just echoes the string of query without execution.

回答1:

You can see the compiled query by either of these functions

/* SELECT */ $this->db->_compile_select();
/* INSERT */ $this->db->_insert();
/* UPDATE */ $this->db->_update();


回答2:

You don't need to change any file in codeigniter because it already provides a method to do that.

Using

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

will produce

select * from some_table...

And this is it.



回答3:

I added this little method in DB_active_rec.php

function return_query()
{
    return $this->_compile_select();
}

Usage

$this->db->select('id,user_name')->from('user')->where('id',1);

$string =   $this->db->return_query();
echo $string;

Result

SELECT `id`, `user_name` FROM (`user`) WHERE `id` = 1

In this way you are bound to use

$this->db->from()

Instead of

$this->db->get()

Which runs the query



回答4:

As of version 3 of Codeigniter, please refer to this url and also to this.

  • echo $this->db->update_string(); OR echo $this->db->get_compiled_update();
  • echo $this->db->insert_string(); OR $this->db->get_compiled_insert();
  • echo $this->db->get_compiled_delete();
  • echo $this->db->get_compiled_select();


回答5:

You can use some public methods to get SQL queries

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