Help with Mysql Query - Subindex_string + group_concat |
Hi guys,
New to CI and having some trouble with a few more advanced SQL queries . I am trying to use substring_index together with group_concat in order to make an array where I have 2 results of each unique group . I have tried the following : Code: $Array = $MyModel Could someone kindly help me fixing my query syntax ? Thanks in advance ! PHP Code: $query = $db->getLastQuery(); What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
(05-06-2021, 07:24 AM)php_rocs Wrote: @tektion, Ah right, thanks for pointing that out didn't pay attention since I was focused on the line causing the syntax issue . Well the problem is the substring_index syntax is not right : Code: CRITICAL - 2021-05-06 15:54:50 --> 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 This is the output I get from this query ! I tried replacing it with Code: ->where(SUBSTRING_INDEX(GROUP_CONCAT('GROUP'),',', 1)) But then I get an invalid function error : Call to undefined function App\Commands\SUBSTRING_INDEX() In the meantime I realized after running the query in MySql that you can't use it as a subquery with where statement so I changed it around and this is what works when I run directly in my database : Code: SELECT SUBSTRING_INDEX(GROUP_CONCAT(id separator ','), ',', 5) So I need to convert this into valid codeigniter format . Tried this : Code: $MyModel->select(SUBSTRING_INDEX(GROUP_CONCAT('id separator ',''), ',', 5)) Which still returns the error : Call to undefined function App\Commands\SUBSTRING_INDEX()
@tektion,
Have you tried the query by using the query binding method instead (https://codeigniter.com/user_guide/datab...y-bindings)? (05-06-2021, 08:49 AM)tektion Wrote: You are using in the select method not a SQL function, but a php function (php thinks so). Therefore, you get an error. Turn it into a string and you will be happy. (05-06-2021, 12:24 PM)php_rocs Wrote: @tektion, Tyvm for the suggestion, seems like the best option for advanced queries indeed as it avoids the need of escaping characters-. Code: $sql = "SELECT SUBSTRING_INDEX(GROUP_CONCAT(id separator ','), ',', 5) FROM `table`"; This works but if possible I would still like to know the proper char escaping to make the query work with my Model, as I am working with arrays and using Models makes life easier . (05-06-2021, 05:57 PM)iRedds Wrote:(05-06-2021, 08:49 AM)tektion Wrote: |
Welcome Guest, Not a member yet? Register Sign In |