如何使用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
$_GETinto your query!). htmlspecialchars()prevents malicious characters from breaking your HTML or triggering XSS attacks.
- Prepared statements eliminate SQL injection risks (never directly insert user input like
- 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 theecholine with:echo htmlspecialchars($medicine) . "<br>";
内容的提问来源于stack exchange,提问作者Muhammad Ahmad
相关产品推荐
相关产品推荐

