Reputation: 23
Here is my coding. I want to view data when i click any row on my table. But it view only the first data on row. What do you think is the problem?
My code on retrieving data from database is working. But when i click it, it always view the data of the first retrieved data row.
<?php
$sql = "SELECT * FROM courses";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered' id='myTable'>";
echo "<tr>";
echo "<th>COURSE CODE</th>";
echo "<th>COURSE NAME</th>";
echo "<th>ACTION</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['course_code'] . "</td>";
echo "<td>" . $row['course_desc'] . "</td>";
echo "<td>";
echo "<a href='#' data-toggle='modal' data-target='#confirmenrollment'>";
echo "Enroll";
echo "</a>";
echo "</td>";
echo "</tr>";
echo "<div class='modal fade' id='confirmenrollment' tabindex='-1' role='dialog'>";
echo "<div class='modal-dialog'>";
echo "<div class='modal-content'>";
echo "<div class='modal-header'>";
echo "<button type='button' class='close' data-dismiss='modal'>×</button>";
echo "<h3>Confirm course to enroll.</h3><br>";
echo "<p><b>Course Name:   </b>" . $row['course_desc'] . "</p>";
echo "<p><b>Course Code:   </b>" . $row['course_code'] . "</p>";
echo "<p><b>Price:   </b>" . $row['course_price'] . "</p>";
echo "<div class='more-button'>";
echo "<a href='#'>";
echo "Confirm Enrollment";
echo "</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No courses found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
Can anyone help me on this?
Upvotes: 2
Views: 143
Reputation: 26450
Your problem is that all your modals has the same DOM ID. You need them to be something unique, and the target to the modal must reflect that, so that each row opens the correct modal.
Assuming that course_code
is unique in the database, you can use that. Then we update the line to open the modal,
echo "<a href='#' data-toggle='modal' data-target='#confirmenrollment-".$row['course_code']."'>";
And the modal ID itself,
echo "<div class='modal fade' id='confirmenrollment-".$row['course_code']."' tabindex='-1' role='dialog'>";
Notice how I appended -".$row['course_code']."
to the data-target
attribute and the modal ID.
Upvotes: 1