Codeigniter Active Record SQL syntax error - php

I have the following Active Record pattern within one of my models :
$this->db->get('names');
$this->db->like('name', $name);
$this->db->where('ratio >=', 0.75);
$this->db->order_by('ratio', 'desc');
$query = $this->db->get();
This gives me a syntax error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `ratio` >= 0.75 AND `name` LIKE '%JORDAN%' ORDER BY `ratio' at line 2
The full statement being returned is :
SELECT * WHERE `ratio` >= 0.75 AND `name` LIKE '%JORDAN%' ORDER BY `ratio` desc
I don't know why my table names isn't showing as I'm calling $this->db->get('names'); which should produce SELECT * FROM names, is it just not returning in the error? What's wrong with this statement and what should I do to correct my Active Record call?

get needs to go at the end. If you want to select a table before - use $this->db->from('names'); and then just $this->db->get();. So the full code:
$this->db->like('name', $name);
$this->db->where('ratio >=', 0.75);
$this->db->order_by('ratio', 'desc');
$query = $this->db->get('names');
or the chaining version:
$query = $this->db->like('name', $name)
->where('ratio >=', 0.75)
->order_by('ratio', 'desc')
->get('names');
Using from:
$query = $this->db->from('names')
->like('name', $name)
->where('ratio >=', 0.75)
->order_by('ratio', 'desc')
->get();

Related

Getting extra quote in query using codeigniter

I am trying to select and join to other table but my query having extra quote unintentionally.
I use this code:
$this->db->select('TA.*, TC.username user FROM tbl_actlog AS TA');
$this->db->join('(SELECT id, username FROM tbl_login) AS TC', 'TC.id = TA.account_id', 'LEFT OUTER');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);
But when my code runs it gives me an error and the output is:
SELECT `TA`.*, `TC`.`username user FROM tbl_actlog` AS `TA`
LEFT OUTER JOIN (SELECT id, username FROM tbl_login) AS TC
ON `TC`.`id` = `TA`.`account_id`
WHERE `TA`.`date_log` >= '2019-12-10' AND `TA`.`date_log` <= '2019-12-10'
ORDER BY `TA`.`act_id` DESC LIMIT 10
MySQL said: Documentation
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near 'LEFT OUTER JOIN (SELECT id, username FROM
tbl_login) AS TC ON `TC`.`id` = `TA`.`' at line 1
From what I understand the right query syntax should be:
$this->db->select('TA.*, TC.id, TC.username');
$this->db->from('tbl_actlog AS TA');
$this->db->join('tbl_login AS TC', 'TC.id = TA.account_id', 'LEFT OUTER');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);
You are not supposed to put the FROM inside your ->select() call. You can make a separate ->from($table_name) call or do ->get($table_name). See documentation.
try following code
$this->db->select('TA.*, TC.username user, TC.id login_id');
$this->db->from('tbl_actlog AS TA');
$this->db->join('tbl_login as TC', 'TC.id = TA.account_id', 'LEFT');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);

combining date and time columns for query in codeigniter

I have a database table with separate date and time column. To get particular I execute query in mysql in following manner
select * from table_A where empID='A1201' order by TIMESTAMP(date,time) desc limit 1
How can I convert this particular for codeigniter? I tried in following manner but it's not working
$column = 'TIMESTAMP(date,time)';
$this->db->select('*');
$this->db->where('empID', 'A1201');
$this->db->from('table_A');
$this->db->order_by($column, 'desc');
$this->db->limit(1);
$query = $this->db->get();
$data = $query->result();
return $data;
This query result in error since it executes in following manner ORDER BY TIMESTAMP(date DESC, time) DESC while the correct way is ORDER BY TIMESTAMP(date,time) DESC. What will be the correct way for codeigniter using active record
try this
$query = $this->db
->select('*')
->where('empID', 'A1201')
->from('table_A')
->order_by($column, 'desc', false)
->limit(1)
->get();
order by comes with a 3rd option - just set this to false
You can get more infos about that in their documentation here

Laravel SQL Query Keeps Giving SQLSTATE[42000]: Syntax error or access violation: 1064

I have this SQL query in my controller at laravel
$distinct_course = DB::table('student')
->select(DB::raw('count(*) as grad_count, `student_course`, MONTH(`student_date_ended`)'))
->where('student_course', '=', 'Basic Computer')
->whereYear('student_date_ended', '=', '2015')
->groupby(DB::raw('MONTH(`student_date_ended`'))
->get();
Which is based on this SQL query I made to work first before converting it to Laravel
select count(*) as grad_count, `student_course`, MONTH(`student_date_ended`) from `student` where `student_course` = "Basic Computer" and year(`student_date_ended`) = 2015 group by MONTH(`student_date_ended`)
But for some reason I always get this error.
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 (SQL: select count(*) as grad_count, student_course, MONTH(student_date_ended) from student where student_course = Basic Computer and year(student_date_ended) = 2015 group by MONTH(student_date_ended)
Am I doing something wrong here that I'm not aware of?
As an alternative, in all my projects I use the following way of DB interactions:
$Query = 'select count(*) as grad_count, `student_course`,
MONTH(`student_date_ended`)
from `student`
where `student_course` = ?
and year(`student_date_ended`) = ?
group by MONTH(`student_date_ended`)';
$GradStudents = DB::select($Query, [ $StudenCourse, $StudentDateEnded]);
This way I can go from confirmed working MySQL statement to Laravel without worrying of call not working after conversion.
Note: Instead of keeping your db calls in the controller, I would them to a model folder. This way you will maintain the MVC design pattern.
With Paul's help I managed to get it working with this code.
$Query = 'select count(*) as grad_count, `student_course`,
MONTH(`student_date_ended`) as Month
from `student`
where `student_course` = ?
and year(`student_date_ended`) = ?
group by MONTH(`student_date_ended`), student_course';
$StudentCourse = 'Basic Computer';
$StudentDateEnded = 2015;
$distinct_course = DB::select($Query, [ $StudentCourse, $StudentDateEnded]);
It would seem that part of the problem was I also needed to add the 'student_course' column in the group by so I tried adding it to my original Laravel code and also managed to get it work with this manner.
$distinct_course = DB::table('student')
->where('student_course', '=', 'Basic Computer')
->whereYear('student_date_ended', '=', '2015')
->select(DB::raw('count(*) as grad_count, `student_course`, MONTH(`student_date_ended`) as Month'))
->groupby(DB::raw('MONTH(`student_date_ended`), student_course'))
->get();

How to display query assembled by ORM?

How to display query assembled by ORM ?
Example: SELECT article.id AS article:id, article.name AS article:name
I'm using the code below:
$query=DB::select('categories.*',
array(DB::expr('COUNT(categories.id)'), 'total'),
array(DB::expr('MIN(displays.price)'), 'min_price'),
array(DB::expr('MAX(displays.price)'), 'max_price'),
array(DB::expr('SUM(displays.is_offer)'), 'is_offer')
)
->from('categories')
->join('category_products', 'INNER')
->on('categories.id', '=', 'category_products.category_id')
->join('displays', 'INNER')
->on('category_products.product_id', '=', 'displays.product_id')
->where('displays.active', '>=', 1)
->group_by('categories.id')
->order_by('parent')
->order_by('total', 'desc');
Let's see, you're using DB::select() which returns a Database_Query_Builder_Select instance. In the doc it says
Database query builder for SELECT statements. See Query Builder for usage and examples.
And if you do see, you'll see
echo Debug::vars((string) $query);
// Should display:
// SELECT `username`, `password` FROM `users` WHERE `username` = 'john'
which makes sense once you see the __toString() from Database_Query_Builder_Select.
So
echo (string) $query;
should give you the query.

Codeigniter active record : how to read the joined table

i have some table, and the relationship goes like this
and i want to get all the record of those 2 tables. so i use this query in my model
$this->db->select('*');
$this->db->from('ms_Kategori_Material.*,ms_Material_Jasa.*');
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
$result = $this->db->get();
$table = $this->db->get();
return $table;
and then i got error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*, `ms_Material_Jasa`.*) JOIN `ms_Material_Jasa` ON `ms_Kategori_Material`.`Kode' at line 2
SELECT * FROM (`ms_Kategori_Material`.*, `ms_Material_Jasa`.*) JOIN `ms_Material_Jasa` ON `ms_Kategori_Material`.`Kode_Kategori_Material_Jasa` = `ms_Material_Jasa`.`Kode_Kategori_Material_Jasa`
why do i can't read the needed table ?
in your from, there shouldnt be a .*,
i.e
$this->db->from('ms_Kategori_Material','ms_Material_Jasa');
and if your adding the table to join, no need to add it to from.
so it becomes
$this->db->from('ms_Kategori_Material');
$this->db->join('ms_Material_Jasa','....');
final query:
$this->db->select('*');
$this->db->from('ms_Kategori_Material');
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
$result = $this->db->get();
$table = $this->db->get();
return $table;
You may try this (to join and select fields from both tables)
$this->db->select('ms_Kategori_Material.*, ms_Material_Jasa.*');
$this->db->from('ms_Kategori_Material');
$this->db->from('ms_Material_Jasa');
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
$table = $this->db->get();
return $table->result();
$this->db->select('*');
$this->db->from('ms_Kategori_Material'); // full table name
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
$result = $this->db->get();
//print_r($this->db->last_query()); display raw sql
$print_r($result->result_array());
Read more # http://codeigniter.com/user_guide/database/active_record.html

Categories