You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单个<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?

  1. Collected Values First: We use a $designations array to store every matching designation name from your database, instead of generating a table cell immediately.
  2. Safe Queries: Swapped direct ID insertion with prepared statements to protect against SQL injection (never skip this if your input comes from user data!).
  3. Single <td> Output: After processing all IDs, we use implode(', ', $designations) to convert the array into a comma-separated string, then print that inside one <td> tag.

内容的提问来源于stack exchange,提问作者Ansh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:49