Codeigniter: does $this->db->last_query(); execute a query? - codeigniter

Does query execution happen at the get_where() clause of the following codeigniter active record statement?
$this->db->select('*');
$q = $this->db->get_where('Contacts', array('id' => $contact_id));
$sql = $this->db->last_query();
Or does it happens once you call the result_array()?
And is $this->db->last_query(); a reliable way in getting the query string.

The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this.
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!!
Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Take a look at this example

For me save_queries option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter

For Me It Works Perfectly: Source Disclosure : This Source website Belongs to me , i am also sharing solutions on my website ...
public function index()
{
$db = \Config\Database::connect();
$heroesCount = $db->table('products')->countAll();
echo $db->getLastQuery();
exit;
}

Related

How to echo the last query after eloquent model in laravel 7?

I am deleting an item like this. The delete method is excuting well but I can't echo the last executed query.
public function deleteItems(Request $request){
$query=null;
switch($request->category){
case('categorylist'):
$category = category::find($request->id);
$query=$category->delete()->toSql();
break;
default:
}
echo json_encode(array('status'=>2, 'msg'=>'Successfully deleted', 'query'=>$query->toSql()));
}
The toSql() method works only on instances of Illuminate\Database\Query\Builder ( query builder as it is usually called ). Methods like where(), orderBy() etc return an instance of query builder, hence toSql() works on them. The delete() method does not return an instance of query builder ( I think it returns Boolean or the id it deleted. Can't remember ). So the toSql() method won't work.
If you just want to get the last executed query, then you could use DB::getQueryLog(). For example
DB::enableQueryLog();
$category->delete();
$queryLog = DB::getQueryLog();
// Now $queryLog will contain all the SQL queries which were executed after the DB::enableQueryLog()
$last = end($queryLog);
$query = $last['query'];
$bindings = $last['bindings'];

Laravel fetch raw query result

I don't want laravel to format my query result to an array or object ..etc. All I want, is to run the result set from database and then I will manually do the fetch myself in my custom code.
At the moment, I ran my select query and get my result in an array. The reasons for that, because the result is huge and I want to stream it directly to API.
$result = self::$db->select('select * from customer');
How can I tell laravel, to return my query result set without any format at all?
You can use DB:Raw like:
$results = DB::table('users')->select(DB::raw("*"))->get()
Or
$results = DB::select('select * from users where id = ?', [1]);
These two will return a neat object without any casts or relations etc. You can also make any object or array your API need by simple eloquent models by the way. Please explain more about data type you wanna extract from model query.
You must be use ->toSql() or ->dd()
Exapmle
Customer::toSql(); // select * from `customer`
if you want some condition
$query = Customer::where(`some conditions`);
$sql = $query->toSql();
$bindings = $query->getBindings();
$sql = str_replace('?', '%s', $sql);
$sql = sprintf($sql, ...$bindings);
Thanks everyone, I end up writing a raw function to query the data I want from database.
public static function dataStreamJSON($stmt, $headers)
{
return Response::stream(function() use ($stmt){
$conn = self::getConnection();
$result = sqlsrv_query($conn, "exec $stmt");
echo '
{
"Customers": {
"Customer": [';
$counter = 0;
while($customer = sqlsrv_fetch_object($result)) {
if($counter !== 0){
echo ",";
}
$counter++;
$row = [
'Firstname' => $customer->Firstname,
'Lastname' => $customer->Lastname,
...
];
echo json_encode($row);
unset($row);
unset($customer);
}
echo ']
}
}';
#sqlsrv_free_stmt($result);
#sqlsrv_close($conn);
}, 200, $headers);
}
The purpose of this code is to stream the data out to JSON format on browser without store the data in any variable, which will caused “out of memory” error.
I managed to stream 700MB of JSON data to the browser without any error. With this code, you will never run into “out of memory” error.
Best way to test this, is to use CURL to access your API and download the data to a JSON file. If you open on browser, it will freeze your screen because browser can't handle large data.
You can use toArray() or toJson() methods like below:
$array = Customer::all()->toArray();
$json = Customer::all()->toJson();
echo '<pre>';
print_r($array);
print_r($json);
If you want to run raw SQL Queries, you can do as below
$users = DB::select('select * from users where 1');
echo '<pre>';
print_r($users);
You can use
1) query builder way:-
DB::table('your_table_name)->select('your_col_names')->get();
eg:- DB::table('shop')->select('product_id','product_name')->get();
2) use laravel Raw
$orders = DB::table('orders')->selectRaw('price * ? as price_with_tax', [1.0825])->get();
3) for select raw
$product_count = DB::table('product')->select(DB::raw('count(*) as total_product_count'))->where('status',1)->get();

Pass specific id to model and take data from database using codeigniter?

My controller method like below
public function index($book_id) {
print_r($book_id);
}
I will get the id from view. View like below
I need to get specific row according id on model how can I do that if I use query in controller its not working
If I use like below in controller it gives something else as result
public function index($book_id) {
print_r($book_id);
$this->db->select('*');
$this->db->from('books')->where('book_id', $book_id);
$query = $this->db->get();
print_r($query);
}
but if I use same query in model with hard coded id for testing it gives the expected out put
Please help me with this
You don't need to include "/index" in anchor tag href as controller default method will be index if found. And "print_r($book_id)" should be "echo $book_id" as $book_id is variable not array.
Please try this code (either in model/controller):
$query = $this->db->get_where('books', array('book_id' => $book_id));
$result = $query->row_array();
print_r($result);

Codeigniter search term with pagination

Still getting to grips with PHP and Codeigniter and I'm having an issue with passing a search term parameter from my Controller to my Model, with pagination.
I have a fully functioning script (with pagination) working already... However, trying to include the input post search term to the model is messing it all up (or I'm messing it all up).
Working script - Controller:
public function search()
{
$this->load->model('Products_model');
$config['base_url'] = base_url() . '/products/search/';
$config['total_rows'] = $this->db->count_all('affiliate_window');
$config['per_page'] = 25;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$data['offset_no'] = $this->uri->segment(3);
$data['items'] = $this->Products_model->get_search($config['per_page'], $data['offset_no']);
$this->load->view('header_view');
$this->load->view('products_view', $data);
$this->load->view('footer_view');
}
Working script - Model:
function get_search($limit, $offset)
{
$query = $this->db->get('mydb', $limit, $offset);
return $query->result();
}
So, any advice on how do I now go about passing $this->input->post('search_term'); from Controller to my model to use like this:
function get_search($limit, $offset)
{
$this->db->like('name', '$SEARCHTERM');
$query = $this->db->get('mydb', $limit, $offset);
return $query->result();
}
Furthermore, I believe I'm next going to run into an issue with keeping the search term variable throughout each page.
Any advice very welcome - I've been working on this for hours with no results! :)
So, understand that your pagination code & all the other code are "unrelated" - meaning, they don't require the other one to function.
You will pass your search term in to your model function like any other parameter & search on it in the query; limit & offset are simply tagged to the end of your query as you are doing now.
So if searching for "myterm", you'll just build a query with:
WHERE term = "myterm" LIMIT offset, limit
It's really quite simple once you get your head around what you are actually doing

Active Record and queries with CodeIgniter

I am using codeigniter for my application and i am a bit confused, I wrote some queries like that:
public function checkemail($email) {
$this->db->select('email')->from('user')->where('email', $email);
}
But in the manual of codeigniter ( http://codeigniter.com/user_guide/database/active_record.html ) they talk about $this->db->get();
Should I add it after the $this->db->select query?
My function works fine...
When should I use get() ?
Thanks you!
Yes, you'll need to run get() after the other methods. select(), from() and where() add their respective statements to the query, and get() actually runs the query and returns the result as an object.
In this case, you could just add it on to the end of the chain.
public function checkemail($email) {
$this->db
->select('email')
->from('user')
->where('email', $email)
->get();
}
If you want to work with the result afterwards, make sure that you are assigning it to a variable.
$user = $this->db
->select('email')
->from('user')
->where('email', $email)
->get();
If you use get("table_name") then you don't need to use from("table_name"). It's just an alternative syntax it seems.
From the user guide, all the way at the bottom it says: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.

Resources