CodeIgniter's GROUP_CONCAT function allows you to concatenate the values

I'm currently having trouble figuring out how to create my group_concat with my SQL request in CodeIgniter. I have a table listing all my queries, using the Jtable library.

Everything works fine except when I attempt to insert GROUP_CONCAT.

Below is my model page :

function list_all()
    {
        $login_id = $this->session->userdata('User_id');
        $this->db->select('p.project_id, p.Project, p.Description, p.Status, p.Thumbnail, t.Template');
        $this->db->from('assigned_projects_ppeople a');
        $this->db->where('people_id', $login_id);
        $this->db->join('projects p', 'p.project_id = a.project_id');
        $this->db->join('project_templates t', 't.template_id = p.template_id');
        $this->db->select('GROUP_CONCAT(u.Asset SEPARATOR ",") as assetslist', FALSE);
        $this->db->from('assigned_assets_pproject b');
        $this->db->join('assets u', 'u.asset_id = b.asset_id');
        $query = $this->db->get();

        $rows = $query->result_array();

        //Return result to jTable
        $jTableResult = array();
        $jTableResult['Result'] = "OK";
        $jTableResult['Records'] = $rows;
        return $jTableResult;
    }

My controller page :

function listRecord(){
        $this->load->model('project_model');
        $result = $this->project_model->list_all();
        print json_encode($result);
    }

Finally, here is my view page :

<table id="listtable"></table>
        <script type="text/javascript">
            $(document).ready(function () {
            $('#listtable').jtable({
                title: 'Table test',
                actions: {
                    listAction: '<?php echo base_url().'project/listRecord';?>',
                    createAction: '/GettingStarted/CreatePerson',
                    updateAction: '/GettingStarted/UpdatePerson',
                    deleteAction: '/GettingStarted/DeletePerson'
                },
                fields: {
                    project_id: {
                        key: true,
                        list: false
                    },
                    Project: {
                        title: 'Project Name'
                    },
                    Description: {
                        title: 'Description'
                    },
                    Status: {
                        title: 'Status',
                        width: '20px'
                    },
                    Thumbnail: {
                        title: 'Thumbnail',
                        display: function (data) {
                            return '<a href="<?php echo base_url('project');?>/' + data.record.project_id + '"><img class="thumbnail" width="50px" height="50px" src="' + data.record.Thumbnail + '" alt="' + data.record.Thumbnail + '" ></a>';
                        }
                    },
                    Template: {
                        title: 'Template'
                    },
                    Asset: {
                        title: 'Assets'
                    },
                    RecordDate: {
                        title: 'Record date',
                        type: 'date',
                        create: false,
                        edit: false
                    }
                }
            });
            //Load person list from server
            $('#listtable').jtable('load');
        });
        </script>

I've read multiple posts discussing this issue, suggesting things like replacing ',' separator with ",", or using OUTER JOIN, or grouping by 'p.project_id' before using the get method, but none of these solutions worked for me.

Here is the output of the query in JSON format :

{"Result":"OK","Records":[{"project_id":"1","Project":"Adam & Eve : A Famous Story","Description":"The story about Adam & Eve reviewed in 3D Animation movie !","Status":"wip","Thumbnail":"http:\/\/localhost\/assets\/images\/thumb\/projectAdamAndEve.png","Template":"Animation Movie","assetslist":"Apple, Adam, Eve, Garden of Eden"}]} 

Although we can see the GROUP_CONCAT is present (after "assetslist"), the column remains empty.

If needed, I can provide the database SQL file.

Answer №1

Would you be able to test out the following code snippet (Updated):

$this->db->select('GROUP_CONCAT(u.Asset) AS assetslist');

Answer №2

It was right in front of me all along, but I completely overlooked it... In order to make GROUP_CONCAT work correctly, you need to use an alias name for the new corresponding column (such as "assetslist"). Make sure to utilize this name in your Jtable configuration instead of the default name of your non-concatenated table column "Asset":

<table id="myListTable"></table>
        <script type="text/javascript">
            $(document).ready(function () {
            $('#myListTable').jtable({
                title: 'My Table',
                actions: {
                    listAction: '<?php echo base_url().'project/listRecords';?>',
                    createAction: '/Projects/AddNewProject',
                    updateAction: '/Projects/EditProject',
                    deleteAction: '/Projects/DeleteProject'
                },
                fields: {
                    project_id: {
                        key: true,
                        list: false
                    },
                    ProjectName: {
                        title: 'Project Name'
                    },
                    Description: {
                        title: 'Description'
                    },
                    Status: {
                        title: 'Status',
                        width: '20px'
                    },
                    Image: {
                        title: 'Image',
                        display: function (data) {
                            return '<a href="<?php echo base_url('project');?>/' + data.record.project_id + '"><img class="thumbnail" width="50px" height="50px" src="' + data.record.Image + '" alt="' + data.record.Image + '" ></a>';
                        }
                    },
                    Template: {
                        title: 'Template'
                    },
                    assetslist: {
                        title: 'Assets'
                    },
                    RecordDate: {
                        title: 'Recorded on',
                        type: 'date',
                        create: false,
                        edit: false
                    }
                }
            });
            //Fetch list of projects from server
            $('#myListTable').jtable('load');
        });
        </script>

Appreciate your help!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from database with the help of PHP and AJAX

I am having trouble printing data from a PHP and Ajax request that is initially encoded into JSON. Instead of displaying the data properly on the screen, it is showing elements from four rows all in a single line with commas separating them. $(document ...

Creating a customized navigation menu for websites containing subdirectories: Tips and techniques

I'm eager to grasp how navigation functions on websites with subdirectories. For instance, if my layout looks like this, \index.php \about_us\about_us.php The navigation link for index.php to return to the homepage would be, ...

Guide for integrating the logic of editAction into showAction within Symfony 2 Doctrine generated CRUD

I have a Symfony 2 project where I've used Doctrine to generate CRUD's for certain entities in my database. Specifically, I have entities named TariffMc and TariffMcServiceMcRelation. A single TariffMc entity can be associated with multiple Tarif ...

Establishing a connection using stream_socket_client that includes the ability to set

Looking at this block of PHP code: $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); The number '60' in the code represents a timeout for the connection establishm ...

What are some examples of utilizing regex case conversion tokens (u l U L E) in PHP code?

Currently, I am trying to allow the user to input both the pattern and the replacement string for the PHP preg_replace function. The following code is functioning correctly: echo preg_replace('/(o)/', ', ${1}h!', 'hello'); / ...

I am interested in placing a button inside an echo table cell

Below is a snippet of my PHP code: echo "<table border='0'>"; while($list = mysql_fetch_assoc($result)) echo "<tr>"; echo "<td>" . $list['SALEPRICE']."</td>"; I am looking to insert a button next to th ...

Implementing a Hands-on Approach to Session Initialization in PHP after Manual

I've implemented a login system that generates a unique token for each login attempt, which is stored in the `$_SESSION['loginToken']` variable. After submitting the login form, it checks if the session value matches the input from the form. ...

Error occurs consistently with AJAX, PHP, and SQL newsfeed

Striving for Progress Currently, I am engrossed in developing a newsfeed and enhancing my proficiency in utilizing Ajax through jQuery. My ultimate aim is to create a seamless user experience where individuals do not need to refresh the page to view the l ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Utilizing MIME to send emails through the Mailgun API, bypassing the need for the Mail

Currently, I am utilizing PHPMailer to generate an email as a MIME string and my intention is to send it through the Mailgun API by using curl to connect to the endpoint /v3/[mydomain]/messages.mime. According to the instructions in the Mailgun documentat ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Find a solution for displaying custom product badges

Having some issues with a custom product badge on my website. I tried adding a new badge (besides "Sale"), but it seems to be displaying in the wrong position. The badge should display as "Choice" on the featured products, so I added this code to the chil ...

Creating a text file and JSON in Laravel 4 framework: A step-by-step guide

Hey there! I have a simple question that I haven't been able to find an answer to. I'm looking to generate a .txt file using Laravel 4 and upload it to my server similar to how PHP does. Additionally, I need to create a JSON file with Laravel 4 ...

Trouble with webpage design persists following recent modifications

Today, I decided to make some alterations on the header.php file of my WordPress website in order to tweak the flag icons displayed at the top of the page. However, when I refreshed the page, everything looked completely chaotic. Even after undoing all th ...

What is the best way to convert every database field into a public variable in PHP?

After running the query below, I have retrieved all database fields: "SHOW COLUMNS FROM admin" Now I am curious about how to convert each field into a public variable within a class structure since I am working with object-oriented PHP. My first step i ...

Passing a range to the search model in Yii2: A step-by-step guide

How can I search within a specific range for a field using the Search Model? Is there a way to implement between, greater than, or less than statements in the search model? I have attempted something like this, but it seems that these attributes are not v ...

Exploring the Magic of Laravel Eloquent: Understanding the Intricacies of a

Recently delving into Laravel-eloquent, I am seeking guidance on transforming this SQL query to Eloquent format: select fl.id, fut.id, fut.firebase_topic_id, ft.id, fl.created_at from firebase_logs fl, firebase_user_topics fut, firebase_to ...

The `terminateSession()` PHP function encapsulated within `$(window).unload`,

I'm currently developing a basic chat script that involves a killSession function. This function's purpose is to terminate the current session and remove the user from the database. However, I am encountering an issue where after setting and veri ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...