mwaniki
mwaniki

Reputation: 25

Loop through table php

Below is a while loop from my php script that populates a HTML table. I want the IF statement at the bottom to set the attribute of <td id="status"></td> depending on its value. But when I run the code, only the value in the first row is set. I guess the problem is with using a single element ID in a loop. Can I use the element ID "status" for every row in the table?

while($row=mysqli_fetch_assoc($result)){
                $dd=strtotime($row["due_date"]);
                $dd=Date('d-m-Y',$dd);
                $bd=strtotime($row["borrow_date"]);
                $bd=Date('d-m-Y',$bd);

                echo '
                <tr>
                <td>'.$row["user_email"].'</td>
                <td>'.$row["last_name"].'</td>
                <td>'.$row["first_name"].'</td>
                <td>'.$row["movie_ID"].'</td>
                <td>'.$row["title"].'</td>
                <td>'.$row["year"].'</td>
                <td>'.$bd.'</td>
                <td>'.$dd.'</td>
                <td id="status"></td>



                </tr>
                ';
                $i++;

                if($dd<$cd){
                    echo' <script type="text/javascript">
                    document.getElementById("status").innerHTML="Overdue";
                    </script>';
                }
                else{
                    echo '
                    <script type="text/javascript">
                    document.getElementById("status").innerHTML="Not Due";
                    </script>';
                }
            }

Upvotes: 0

Views: 48

Answers (2)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

Simply you can do in php itself

if($dd<$cd){
      echo '<td>Overdue</td>';  
     }else{
     echo  '<td>Not Due</td>';
    }  

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

First of all - you cannot use same id for multiple elements.

Read function name: getElementById. See - Element, not Elements. That's why using getElementById returns you only first element.

Going further - you can check you condition in php (using simple ternary operator, for example) and forget about javascript:

    // previous code here
    '<td>'.$dd.'</td>
    <td>' . ($dd<$cd? 'Overdue' : 'Not Due') . '</td>
</tr>';
$i++;

Upvotes: 3

Related Questions