PHP MySQL Result in div

I'm encountering a problem with regards to my codes in PHP. My for each code isn't working well for the result of my query supposed to be the list column show 2 documents for the year 1990 for the document type Policies but it only shows 1 document. This is what the result looks like:

RESULT

This is what my table looks like:

DOCUMENTS TABLE

This is my code:

<div class="box-body">
    <div class="panel-group">
        <?php 
            $sql = "select document_type, document_title , issued_year from documents WHERE document_type=document_type GROUP BY document_type, issued_year";
            $query = $dbh->prepare($sql);
            $query->execute();
            $results=$query->fetchAll(PDO::FETCH_OBJ);
            if ( $query->rowCount() > 0 ) {
                foreach ($results as $result) {         
        ?>
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" href="#<?php echo htmlentities($result->document_type.$result->issued_year);?>"><?php echo htmlentities($result->document_type);?></a>
                </h4>
            </div>
            <div id="<?php echo htmlentities($result->document_type.$result->issued_year);?>" class="panel-collapse collapse">
                <ul class="list-group">
                    <li class="list-group-item"><?php echo htmlentities($result->issued_year);?>
                        <ul>
                            <li><a href="../documents/<?php echo htmlentities($result->filename);?>"><?php echo htmlentities($result->document_title);?></a></li>   
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
        <?php }
        }?>
        <br>
    </div>

1 answer

  • answered 2019-10-08 07:30 Lucek

    You don't need a GROUP BY in your query. When you group by type and year you aggregate records with the same type - year combination for aggregate functions like MAX or AVERAGE. If you want a list of documents with type 'Policies and year 1990 your query should look like this:

    SELECT document_type, document_title , issued_year 
    FROM documents 
    WHERE document_type = 'Policies' AND issued_year = '1990'