Search code examples
phpmysqllistcell

Lists inside the cell and output it the same way in php


Is it possible to make a list inside the cell of a table in mysql and outputs it the same way when being retrieved through php? I've been trying to work it out but I don't know if it's possible.

Sample of this is in my packages table I have a column_name (Inclusions) and in every cell it has lists of data separated by new line. But whenever I retrieve it in php, it displays in one sentence.


Solution

  • While Barmar is correct, I would suggest a design change in your database. Instead of listing several values in a single cell, you should have a separate entry for each value and reference it to the list name.

        +-----------+   +------------------+
        | List_Name |   | List_Item        |
        |-----------|   |------------------|
        | ID | Name |   | List_ID | Value  |
        | 0  | Frt  |   | 0       | Apple  |
        | 1  | Veg  |   | 1       | Tomato |
        +-----------+   | 1       | Potato |
                        | 0       | Pear   |
                        +------------------+
    

    Querying by List_Name:

        SELECT b.Value
        FROM List_Item b
        JOIN List_Name a ON b.List_ID = a.ID
        WHERE a.Name = 'Frt'
    

    Return all of the values:

        SELECT b.Value
        FROM List_Item b
        JOIN List_Name a ON b.List_ID = a.ID
    

    Return all of the values and order by name:

        SELECT b.Value
        FROM List_Item b
        JOIN List_Name a ON b.List_ID = a.ID
        ORDER BY a.Name ASC | DESC
    

    Return individual values:

        SELECT b.Value
        FROM List_Item b
        JOIN List_Name a ON b.List_ID = a.ID
        WHERE b.Value = 'Apple'
    

    This will give you the raw output: Apple Pear (you can manually add a line break)

    Of course, you can combine this with a loop and you can add a line break with php.

    Edit: It took me a while to type this, and I did not see the edit on Barmar's answer.