如何在单个<td>中按ID展示逗号分隔的迭代值?
Got it, let's fix this so all your designations end up in one <td> instead of multiple ones. Here's how to adjust your code:
Step-by-Step Solution
The key issue right now is you're generating a <td> inside your loop. Instead, we'll collect all the matching designation values first, then output them in a single table cell separated by commas.
Modified Code (Using PDO for Safe Queries)
<?php $des_cc = explode(',', $designation_cc_email); $designations = []; // Empty array to store fetched designation names foreach($des_cc as $out) { // Use prepared statements to avoid SQL injection (critical security practice!) $sql_reporting1 = "SELECT designation FROM tbl WHERE id = ?"; $stmt = $pdo->prepare($sql_reporting1); $stmt->execute([$out]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result) { $designations[] = $result['designation']; // Add each valid designation to our array } } // Now turn the array into a comma-separated string and place it in one <td> ?> <td><?php echo implode(', ', $designations); ?></td>
If You're Using MySQLi Instead of PDO
Adjust the loop part to match MySQLi syntax:
foreach($des_cc as $out) { $sql_reporting1 = "SELECT designation FROM tbl WHERE id = ?"; $stmt = $mysqli->prepare($sql_reporting1); $stmt->bind_param("i", $out); // "i" = integer (use "s" if your ID is a string) $stmt->execute(); $result = $stmt->get_result()->fetch_assoc(); if ($result) { $designations[] = $result['designation']; } }
What Changed?
- Collected Values First: We use a
$designationsarray to store every matching designation name from your database, instead of generating a table cell immediately. - Safe Queries: Swapped direct ID insertion with prepared statements to protect against SQL injection (never skip this if your input comes from user data!).
- Single
<td>Output: After processing all IDs, we useimplode(', ', $designations)to convert the array into a comma-separated string, then print that inside one<td>tag.
内容的提问来源于stack exchange,提问作者Ansh
相关产品推荐
相关产品推荐

