Welcome Guest, Not a member yet? Register   Sign In
Problem to execute a mysql query with cast
#1

[eluser]Ricardo SDL[/eluser]
Hello fellows! I'm trying to execute a query like this using the codeigniter database class:
Code:
$ci->db->select('engine_types.*, cast(engine_types.name as decimal(5,1)) as name_numeric');
$ci->db->order_by('name_numeric', 'asc');
$query = $ci->db->get_where('engine_types', array('id_vehicle_type' => $id_vehicle_type));
But I'm receiving this error message:

A Database Error Occurred

Error Number: 1064

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 '`1))` as name_numeric FROM (`engine_types`) WHERE `id_vehicle_type` = 2 ORDER BY' at line 1

SELECT `engine_types`.*, cast(engine_types.name as decimal(5, `1))` as name_numeric FROM (`engine_types`) WHERE `id_vehicle_type` = 2 ORDER BY `engine_types`.`name_numeric` asc

The query executes correctly in phpmyadmin. The mysql version is 5.0.67-0ubuntu6 and the CI version is 1.7.2. Any idea of what is wrong?
Thanks in advance!
#2

[eluser]bgreene[/eluser]
using an sql editor, your select statement didnt work but both of these did
select e.*, cast(e.name as decimal(5,1)) as name_numeric from engine_types e
select *, cast(name as decimal(5,1)) as name_numeric from engine_types
#3

[eluser]Ricardo SDL[/eluser]
I've tried this way:
Code:
$ci->db->select('* , cast(name AS decimal(5, 1)) AS name_numeric');
$ci->db->order_by('name_numeric', 'asc');
$query = $ci->db->get_where('engine_types', array('id_vehicle_type' => $id_vehicle_type));

I've got the same error message:

A Database Error Occurred

Error Number: 1064

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 '`1))` AS name_numeric FROM (`engine_types`) WHERE `id_vehicle_type` = 2 ORDER BY' at line 1

SELECT *, cast(name AS decimal(5, `1))` AS name_numeric FROM (`engine_types`) WHERE `id_vehicle_type` = 2 ORDER BY `name_numeric` asc

I think that these quotes shouldn't be here: cast(name AS decimal(5, `1))`
Is the active record generating the wrong sql?
#4

[eluser]bgreene[/eluser]
why not check it with a simple query?
$sql = sprintf('select e.*, cast(e.name as decimal(5,1)) as name_numeric from engine_types e where (e.id_vehicle_type = %d) order by name_numeric asc', $id_vehicle_type);
$qry = $this->db->query($sql);
#5

[eluser]rogierb[/eluser]
Ci is escaping your select.

Try
Code:
$ci->db->select('* , cast(name AS decimal(5, 1)) AS name_numeric',false);
#6

[eluser]Ricardo SDL[/eluser]
Thanks rogierb, bgreene. The tip about the escaping worked.




Theme © iAndrew 2016 - Forum software by © MyBB