John Davidson

php - Print table cells side-by-side with survey responses

0 comments
Message:


I'm getting survey responses. I'm trying to list these answers by making a table.
Every 4 records represent 4 answers on 4 questions. The goal is to print them side-by-side in one row.


Data from DB:


id      user_id     question_id     gsm     answer          date

1 1 1 xxxx 3 2021.08.08
2 1 2 xxxx 2 2021.08.08
3 1 3 xxxx 1 2021.08.08
4 1 4 xxxx comment 2021.08.08

5 1 1 xxxx 3 2021.08.08
6 1 2 xxxx 2 2021.08.08
7 1 3 xxxx 1 2021.08.08
8 1 4 xxxx comment 2021.08.08


<table style="width: 100%;" id="example2" class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>user</th>
<th>Question1</th>
<th>Question2</th>
<th>Question3</th>
<th>Question4(Comment)</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
$sql=$db->query("SELECT * FROM `table` WHERE `user_id` = '".$user_id."' ");
foreach($sql as $rows){
?>
<tr>
<td><?php echo $sql['user_id']; ?></td>
<td><?php echo $sql['answer']; ?></td>
<td><?php echo $sql['answer']; ?></td>
<td><?php echo $sql['answer']; ?></td>
<td><?php echo $sql['answer']; ?></td>
<td><?php echo $sql['date']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

How could I print all 4 records (answers) side-by-side in one tr for users from DB?



My Answer:
Here is a PHP code snippet that fetches the survey responses from the database and prints them side-by-side in a table:

php
// Assuming you have already connected to the database

// Fetch survey responses from the database
$query = "SELECT * FROM survey_responses";
$result = mysqli_query($conn, $query);

// Check if there are any results
if (mysqli_num_rows($result) > 0) {
echo "";
while ($row = mysqli_fetch_assoc($result)) {
echo "";
echo "";
if (mysqli_num_rows($result) % 4 == 0) {
echo "";
}
}
echo "";
echo "
{$row['answer']}
";
} else {
echo "No survey responses found.";
}
?>


This code snippet fetches the survey responses from the database and prints them in a table. It checks if the number of rows fetched is a multiple of 4 and starts a new row in the table accordingly.

Rate this post

3 of 5 based on 5430 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us