Use where and like in Ignited Datatables - php

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

Related

What's the equivalent of $this->db->last_query() in Codeigniter 4?

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;

CodeIgniter Model Function, getting synatx error

I have written one codeigniter model function, but getting syntax error in php 7.. will you please suggest me changes
Error near group by order by statements..
My Code Snippet:
function listing($searchText = '', $page, $segment)
{
$this->db->select('tr.*,group_concat(tg.groundname) as grplist ');
$this->db->from('tb_tournament as tr ');
$this->db->join('tournamentground as tg', 'tr.tournamentId=tg.tournamentId', 'left');
$this->db->where('tr.is_deleted','0');
if(!empty($searchText)) {
$likeCriteria = " (tr.organizerName LIKE '%".$searchText."%'
OR tr.location LIKE '%".$searchText."%'
OR tr.phone LIKE '%".$searchText."%'
OR tr.email LIKE '%".$searchText."%'
OR tr.level LIKE '%".$searchText."%'
OR tr.gender LIKE '%".$searchText."%')";
$this->db->where($likeCriteria);
}
$this->db->group_by('tr.tournamentId');
$this->db->order_by('tr.tournamentId', 'DESC');
$this->db->limit($page, $segment);
$query = $this->db->get();
$result = $query->result();
//print"<pre>";
//print_r($result);
return $result;
}
You can use following logic in your query:
....
$this->db->or_like('tr.organizerName',$searchText);
$this->db->or_like('tr.location',$searchText);
....
....
It's done :)
The error is with the SQL query being generated, not from PHP.
Instead of this big where condition you need need to use query grouping as outlined in https://www.codeigniter.com/user_guide/database/query_builder.html#query-grouping
$likeCriteria = " (tr.organizerName LIKE '%".$searchText."%'
OR tr.location LIKE '%".$searchText."%'
OR tr.phone LIKE '%".$searchText."%'
OR tr.email LIKE '%".$searchText."%'
OR tr.level LIKE '%".$searchText."%'
OR tr.gender LIKE '%".$searchText."%')";
$this->db->where($likeCriteria);
I haven't actually used codeIgnitor, but based on a quick look at the docs you probably need to replace the problematic block with something like this:
$this->db->group_start()
->or_where(tr.organizerName LIKE "%{$searchText}%")
->or_where(tr.location LIKE "%{$searchText}%")
->or_where(tr.phone LIKE "%{$searchText}%")
->or_where(tr.email LIKE "%{$searchText}%")
->or_where(tr.level LIKE "%{$searchText}%")
->or_where(tr.gender LIKE "%{$searchText}%")
->group_end();
It's worth noting that you could use some business logic to improve this query as well. For instance you could recognise when the search term is a phone number, or an email and restrict the query accordingly
here is my solution with query grouping
function listing($searchText = '', $page, $segment)
{
$this->db->select('tr.*,group_concat(tg.groundname) as grplist ');
$this->db->from('tb_tournament as tr ');
$this->db->join('tournamentground as tg', 'tr.tournamentId=tg.tournamentId', 'left');
$this->db->where('tr.is_deleted','0');
if(!empty($searchText)) {
$this->db->group_start()
$this->db->like('tr.organizerName',$searchText);
$this->db->or_like('tr.location',$searchText);
$thsi->db->group_end()
}
$this->db->group_by('tr.tournamentId');
$this->db->order_by('tr.tournamentId', 'DESC');
$this->db->limit($page, $segment);
$query = $this->db->get();
$result = $query->result();
//print"<pre>";
//print_r($result);
return $result;
}
Read more about query grouping here
https://www.codeigniter.com/user_guide/database/query_builder.html#query-grouping

Codeigniter : how to write a query when the inside of the table have value ""

I've got a table in which a field contains pattern Like this [{"vendor":"10","status":"paid"}] :
table
I want to make a query 'like' in codeigniter , but I got an error:
model :
function get_total_order($id_vendor){
$this->db->like('payment_status', 'vendor":"'.$id_vendor.'","status":"due');
$this->db->from('sale');
return $this->db->count_all_results();
}
view :
<?php
$new_order = $this->crud_model->get_total_order($this->session->userdata('vendor_id'));
echo "<h1>".$new_order."</h1>";
?>
when i run this, i got blank page, how i fix this?
thanks.
Since you use "Like" query type, you should add '%' in the query argument or send a complete argument:
function get_total_order($id_vendor)
{
$this->db->like('payment_status', '%vendor":"'.$id_vendor.'","status":"due%');
$this->db->from('sale');
return $this->db->count_all_results();
}
Try this:
function get_total_order($id_vendor){
$this->db->like('vendor',$id_vendor);
$this->db->like('status',"due");
$this->db->from('sale');
return $this->db->count_all_results();
}
if your searching json data so you have pass the data in like query and like query data should be look like data inside the table how it looks .
your query should be something like this
<?php
$id_vendor =123;
$ss= '%"vendor":"'.$id_vendor.'","status":"due"%';
$sssss ="select * from sale where payment_status like '$ss' ";
echo $sssss;
query look like this
select * from sale where payment_status like '%"vendor":"123","status":"due"%'
?>
and also you can use wildcard (%) more place with your wish.
You can customize where as per your requirement with and condition or another condition.
$where = "payment_status like '%$id_vendor%' OR status like '%$status%'";
$this->db->where($where);
try this one:
Because 'like is time consuming.
function get_total_order($id,$vendor)
{
$this->db->where('vender', $id);
$this->db->where('status',$vendor);
$this->db->get('sale');
$result=$res->result_array();
return $result;
}
You can use $this->db->where_in() like below:-
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
For more details, please check below link:-
https://www.codeigniter.com/userguide2/database/active_record.html

Yii-How to write this query in yii?

I am trying to fetch the no of records, but I am unable to write this query in yii. My sql query is given below.
select count(review) from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01')) . I am currently writing this query in yii is given below.
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created'>=DATE_FORMAT(NOW() ,'%Y-11-01'))
->queryAll();
But I am getting this error Fatal error: Call to undefined function NOW() in G:\www\ba.dev\protected\views\business\stats.php on line 19. I am sure it is because of my poor yii query. Kindly correct my query.
If you are willing to run the entire query and not use the active record pattern You can try built-in YII commands to do that.
$query = 'select * from post where category=:category';
$list= Yii::app()->db->createCommand($query)->bindValue('category',$category)->queryAll();
Explanation: $query should be obvious and =:category is binding the variable category dynamically to the query for security reasons. In next line I am creating the query and substituting the value of category variable by using bindValue() function, finally queryAll retrieves all the records in the database. Hope it is clear now.
In your case
$query = "select count(review) as result from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01'))" ;
$list= Yii::app()->db->createCommand($query)->queryAll();
Now you can access the result like this:
foreach ($rows as $row) {
$result = $row["result"];
}
Try this,
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created >=DATE_FORMAT(NOW() ,"%Y-11-01")')
->queryScalar();

CodeIgniter Select Statement with Where clause

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

Categories