So I have inherited a table that holds data collected from a webform, but stacks all the responses into one column like below - there are a lot more rows than this but this is an example,
U_ID Q_ID textResponse
1 1 jon
1 2 toomey
1 3 some@email.com
1 4 NULL
1 5 NULL
2 1 bob
2 2 smith
2 3 another@email.com
2 4 NULL
2 5 NULL
3 1 jim
3 2 kirk
3 3 captains@log.com
3 4 NULL
3 5 NULL
I need to seperate all the responses for each person into rows and ignore the NULL entries.
I want it to look like this,
Name Surname Email
jon toomey some@email.com
bob smith another@email.com
jim kirk captains@log.com
The SQL I've been trying looks like this,
$sql = "
SELECT
CASE
WHEN q_id = 1 THEN textResponse
END AS Name
FROM Responses
UNION
SELECT
CASE
WHEN q_id = 2 THEN textResponse
END AS Surname
FROM Responses
UNION
SELECT
CASE
WHEN q_id = 3 THEN textResponse
END AS Email
FROM Responses
";
The PHP I've written looks like this,
<?php while ($rows = $result->fetch_assoc()){ ?>
<tr>
<?php
foreach ($rows as $row)
echo "<td>" . $row . "</td>";
?>
</tr>
<?php
}
?>
but it's just giving me everything in one line, rather than three columns
MySQL 5.7.18 PHP 5.3.3
Any ideas?
Cheers Jon
It would be much easier to do this in your php code:
First get everything by
SELECT `Q_ID`, `textResponse` FROM `Responses` ORDER BY `U_ID`, `Q_ID`
Then in your while do something like this
$table_rows = '';
while($row = $result->fetch_assoc()) {
switch($row['Q_ID']) {
case '1':
$table_rows .= '<tr><td>' . $row['textResponse'] . '</td>';
break;
case '2':
case '3':
$table_rows .= '<td>' . $row['textResponse'] . '</td>';
break;
case '4':
$table_rows .= '</tr>';
break;
}
}
Lastly, wrap it in proper table markup and send it back:
die('<table><tbody>' . $table_rows . '</tbody></table>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.