I just started learning Codeigniter 4. My query always generates NULL and I don't know why. How can I see the generated SQL Select command just like Codeigniter 3?
In Codeigniter 3 this command does the job:
echo $this->db->last_query();
And this is my controller code in Codeigniter 4 that I need to get the generated query:
$cityModel = new CityModel();
$cities = $cityModel
->select('city.name AS cityName')
->select('county.name AS countryName')
->select('province.name AS provinceName')
->join('province', 'city.province_id = province.id', 'left')
->join('county', 'city.county_id = county.id', 'left')
->result();
Update:
I tried this code but it's returning an empty string:
var_export((string)$cityModel->db->getLastQuery());
This should display the final query:
$cityModel->getLastQuery()->getQuery()
In CI 4 Refer Doc
you can use getLastQuery() as
$query = $db->getLastQuery();
echo (string)$query;
This code will help you to get the last query in codeigniter 4.
$this->db = \Config\Database::connect();
$data = $builder->get()->getResult();
echo $this->db->getLastQuery(); die;
You can use getCompiledSelect it will return the query SELECT command.
$sql = $cityModel->getCompiledSelect();
echo $sql;
Following Code will work in CI 4
$this->db->getLastQuery()->getQuery();
Simply just use $this->db->getLastQuery();
This worked for me
$myModel = new MyModel();// your any model
$myModel->db->getLastQuery()->getQuery();
$this->db is not directly accessible from controller, but if you have any Model instance then you can have the full access to db object.
Add this code in your class
$db = \Config\Database::connect();
$query = $db->getLastQuery();
echo $query;
Related
I am trying to join two tables and return an array in my Model method in CodeIgniter with php. I've gone through a few previously posted similar questions on stackoverflow and modified my code accordingly. But they don't seem to work. Hence would love to know what's wrong with the following.
I'm using the following method but am currently getting exceptions. Would appreciate suggestions in this regard.
Model Method
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
$this->db->from('sysuser as s');
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left');
$this->db->where(array('s.uid' => $uid));
$query = $this->db->get();
return $query->result();
}
Controller
$data1['details'] = $this->userModel->getUserDetails($username);
$this->load->view('studentDashboard/viewProfile',$data1);
View
...
<h2>
<?php foreach($details as $detail){?>
<?php echo $detail->s.name;?>
<?php }?>
</h2>
...
In the view, I've also tried just echoing $detail->name but this doesn't work either.
At first, use print_r($details) for checking your data. If it's returning anything or not.
Then echo your value like this $detail['name']
Fixed Code:
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
$this->db->select("*");
$this->db->from('sysuser');
$this->db->join('studentprofile', 'studentprofile.uid = sysuser.uid');
$this->db->where('sysuser.uid',$uid);
$query = $this->db->get();
return $query->result();
}
Look, i´m not sure that i understood your code, what means this line
$uid = $this->getUserUid($username);
You´re calling a method and sending the name to retrieve the userid, right?
I´ll write that method like you should have it:
public function getUserid($user){
$this->where->id($user);
return $this->get('whatever table')->row();
//i think you forgot this ->row()
}
then
public function getUserDetails($username)
{
$uid = $this->getUserUid($username);
//here already you should bring with ->row() already
//you can use this var_dump here to confirm too
//var_dump($uid);
//exit;
$this->db->select('s.uid, s.name,s.phone, s.studentId, s.type, sp.profiledesc, sp.age');
//line´s right
//the from method is disposable, so i put it into the get but here it´s right too
$this->db->join('studentprofile as sp', 's.uid = sp.uid', 'left'); //ok
$this->db->where($uid); //this line is the wronger, i´ve made the fix
//as this is an where, you´d bring only one value with ->row() from that other method
$query = $this->db->get('sysuser as s');
//the 'from' i putted here, just to write a line less
return $query->result();
when you need to test what you´re returng do a var_dump here
//commenting the return above
//$test = $query->result();
//var_dump($test);
}
I'm trying to execute SQL query with table gateway which contain COUNT(*) expression in ZF2. This is function in my model:
public function brKomentariUred(){
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$select->columns(array('brKomentari' => new \Zend\Db\Sql\Expression('count(komentarID)'), 'uredId' => 'ured'));
$select->group('ured');
//echo $sql->getSqlStringForSqlObject($select); die();
return $this->tableGateway->selectWith($select);
}
When the query is printed it is correct
SELECT count(komentarID) AS `brKomentari`, `komentar`.`ured` AS `uredId` FROM `komentar` GROUP BY `ured`
In the controller I'm trying to call the query with this code
foreach($this->getKomentarTable()->brKomentariUred() as $r){
$arr = $this->object_to_array($r);
print_r($arr);
}
It doesn't return number of elements and devicesID as it is written in SELECT, but return as SELECT * FROM komentar, but with no values. Is this right code or I'm making some error in my code? Other queries are OK.
Thanks in advance for your help.
In your place I would do the following steps:
replace the expression object with new \Zend\Db\Sql\Expression('COUNT(komentarID)')
I wouldn't use an alias in group by operator, it may not work. So,
replace this $select->group('ured') with
$select->group('komentar.ured')
Also, the result processing should be simplified:
$resultSet = $this->getKomentarTable()->brKomentariUred();
print_r($resultSet->toArray());
Hi I'm new to CodeIgniter and I just want to know How will I query from my MySql Db, a Select Statement with a where clause, I know it can be searched from the net but whenever I try something I get errors, It's really frustrating. The string in the Where clause will be coming from a User Input. Thanks guys!
You can do as Mehedi-PSTU stated, however it seems as though you're a little new to this, so here's some extra information:
I'll copy Mehedi-PSTU for the most part here.
$this->get->where('column_name', $equals_this_variable);
$query = $this->db->get('table_name');
This will store the query object in the variable $query.
if you wanted to convert that to a usable array, you just perform to following.
$results = $query->result_array();
Or you can loop through it like this:
foreach($query->result_array() as $result){
// Perform some task here.
}
A better or even full understanding can probably come from:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
Try something like this
$this->db->where('db_attr', $var);
return $this->db->get('table');
Try this one.
$id = 'your id';
$this->db->select("*");
$this->db->from("table_name");
$this->db->where('id','$id');
$query = $this->db->get();
return $query->result_array();
In Codeigniter with Method Chaining Style :-
$data['getData'] = $this->db->get_where('table_name',array('column_name'=>$var))->result_array();
how to implement Where and Like using Ignited Datatables for codeigniter while building query to get result.
Code i have tried is below:
$meter_id="12345";
$meter_id="'%".$meter_id."%'";
$this
->datatables
->select('Log_Name,Log_Creation_Date_Time,User_Name')
->from('Log_Data')
->where('Log_Name LIKE', $meter_id); //(Trying to Build LIke statement Here)
echo $this->datatables->generate();
OR
$meter_id="12345";
$this
->datatables
->select('Log_Name,Log_Creation_Date_Time,User_Name')
->from('Log_Data')
->like('Log_Name', $meter_id);
echo $this->datatables->generate();
But above both code was not working.
i have also check the documentation of Ignited Datatables of Codeigniter but not found any example to bulid query with LIKE Keyword.
Query i have to build:
SELECT
Log_Name,
Log_Creation_Date_Time,
User_Name
FROM Log_Data
WHERE Log_Name LIKE '%12345%'
How could i will implement this?
Try like
$meter_id="12345";
$this->db->select('Log_Name,Log_Creation_Date_Time,User_Name')
->from('Log_Data')
->like('Log_Name', $meter_id);
$result = $this->db->get();
print_r($result);
Try this
$meter_id="12345";
$this->db->select('Log_Name,Log_Creation_Date_Time,User_Name');
$this->db->like('Log_Name', $meter_id);
$query = $this->db->get('Log_Data');
$result = $query->result();
print_r($result);
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.
You can see the compiled query by either of these functions
/* SELECT */ $this->db->_compile_select();
/* INSERT */ $this->db->_insert();
/* UPDATE */ $this->db->_update();
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.
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
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();
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();
From CI 3.1.11 The below code will help you
$this->db->get_compiled_select()
Form more details visit https://codeigniter.com/userguide3/database/query_builder.html#selecting-data