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

如何使用PHP将MySQL表中逗号分隔的列值逐行输出

Solution to Split Comma-Separated Medicine Names into Individual Lines

Got it, let's adjust your code so each medicine name from the comma-separated list shows up on its own line. Here's the modified version with key improvements:

<?php
// Fix SQL injection vulnerability with prepared statements (critical security step!)
$patientId = $_GET['ipd_patientid'];
$stmt = mysqli_prepare($conn, "SELECT ipd_medicine_name FROM `ipd_patients` WHERE ipd_patientid = ?");
mysqli_stmt_bind_param($stmt, "i", $patientId); // Use "s" instead of "i" if patient ID is a string
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

while($data = mysqli_fetch_array($result)) {
    // Split the comma-separated string into an array of medicine names
    $medicineList = explode(',', $data['ipd_medicine_name']);
    // Trim extra spaces from each name (handles cases like "Aspirin, Paracetamol")
    $medicineList = array_map('trim', $medicineList);
    
    // Loop through each name and display it on a new line
    foreach ($medicineList as $medicine) {
        // Prevent XSS attacks with htmlspecialchars
        echo "<p>" . htmlspecialchars($medicine) . "</p>";
    }
}

// Clean up the database statement
mysqli_stmt_close($stmt);
?>

What Changed & Why:

  • Splitting the String: explode(',', $data['ipd_medicine_name']) breaks the comma-separated value into an array of individual medicine names.
  • Trimming Whitespace: array_map('trim', $medicineList) removes any leading/trailing spaces from each entry, so you don't get extra blank space in your output.
  • Security Fixes:
    • Prepared statements eliminate SQL injection risks (never directly insert user input like $_GET into your query!).
    • htmlspecialchars() prevents malicious characters from breaking your HTML or triggering XSS attacks.
  • Line Breaks: Using separate <p> tags ensures each name is on its own distinct line. If you prefer all names in one paragraph with line breaks, replace the echo line with:
    echo htmlspecialchars($medicine) . "<br>";
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:27:48