MRDV
MRDV

Reputation: 45

fetchAll() is printing the data twice

I'm having a problem when I fetch data using 2 foreach()

The problem when I load the page I get the same row twice.

For example $row['1']:

$row['1'] = "Name";

I get this :

NAME
NAME

My code :

$query = "SELECT gid,group_time,name_student,certificate_id,course_id,course_title,course_days FROM  groups JOIN students JOIN courses  WHERE group_id = ? ";
$q = $connection->prepare($query);
if(!$q){

  die("rip".mysqli_error($connection));
}
$q->bindparam(1,$gid);
$q->execute();
$all = $q->fetchAll(PDO::FETCH_ASSOC);

This is my table :

<table dir="rtl" class="table table-bordered table-striped table-hover">
            <thead>

<tr>


    <th class="text-center">name of student</th>

    <?php
    foreach($all as $r2){

      echo '<div dir="ltr"class="h4 text-center " style="text-decoration:underline;text-decoration-skip: ink;">report</div>';
      echo '<div dir="ltr"class="h3 text-center" style="text-decoration:underline;text-decoration-skip: ink;">'.$r2['course_title'].'('.$r2['group_time'].')</div>';
echo "<br>";
    for ($i = 1; $i <= $r2['course_days']; $i++) {

        echo "<td class='text-center'>$i</td>";
    }

}

    ?>

</tr>
</thead>
<tbody>



<?php
foreach($all as $r){
echo "<tr>";
print "<td class='text-center'>".$r['name_student']."</td>";

for ($i = 1; $i <= $r['course_days']; $i++) {

    print "<td></td>";
}
echo "</tr>";

}

?>


</tbody>

</table>

screenshot of the problem : enter image description here So I saw couple questions about the same topic But all the solutions didn't work for :\

I tried to use :

$q->fetchAll(PDO::FETCH_ASSOC);

Instead of fetchAll();

But it is not working.

Its the same problem if i used while loop

Upvotes: 2

Views: 234

Answers (1)

Thomas G
Thomas G

Reputation: 10216

Assuming your DB is MySQL.

Your PHP code looks fine but this query can hardly be correct and is probably the source of your issue :

SELECT id,group_time,name_student,certificate_id,course_id,course_title,course_days 
FROM  groups 
JOIN students 
JOIN courses  
WHERE group_id = ? 

Your JOINs don't have a ON clause. This means they are interpreted as CROSS JOIN, this results in a Cartesian product between your 3 tables. And so you have too much rows returned

You should do something like

SELECT id,group_time,name_student,certificate_id,course_id,course_title,course_days     
FROM  groups G
JOIN students S ON G.id=S.group_id
JOIN courses  C ON G.id=C.group_id
WHERE group_id = ? 

Its impossible to give you the right answer for your query since you have not shown the structure of your 3 tables

Upvotes: 1

Related Questions