如何从PHP/MySQL提取逗号分隔值并转为按钮展示
Hey there! Let's break down what's going on with your size display issue and fix it step by step.
You've successfully stored multi-select sizes in your database using implode(', ', $array) (resulting in formats like 2, 3, 4), but hit a snag when trying to display them as button/link elements—only a single size was showing up instead of all selected ones.
Looking at your original extraction code:
while($row_t4 = mysqli_fetch_array($run_get_sizes)){ $pr_sizes = $row_t4['size_title']; foreach($pr_sizes as $key=>$value){ // ... output $value } }
The core issue here is that $row_t4['size_title'] is a single string (e.g., "2") for each row returned by your query—not an array. The foreach loop doesn't work as expected here, and you end up only rendering the last size fetched.
The final code you landed on is the right approach—let's break down how it fixes the problem:
Collect all size links first
Create an empty array to store each formatted size link. Loop through your query results, wrap each size in the desired HTML, and push it into the array:$availableSizeArr = []; while($row_t4 = mysqli_fetch_array($run_get_sizes)){ $pr_sizes = $row_t4['size_title']; $availableSizeArr[] = "<a href='shop-sidebar.php' rel='tag'>$pr_sizes</a>"; }Combine links into a display-ready string
Useimplode(', ', $availableSizeArr)to join all the links with a comma and space, so you can output them all at once:$availableSizes = implode(', ', $availableSizeArr);Render in your modal
Replace the single$valuein your modal HTML with$availableSizes:<span class='posted_in font-size-12'>Available Sizes - $availableSizes</span>
- Simplify your insertion code: You don't need to
implodeon every loop iteration—do it once after collecting all values:$tshirt_sizes_array = []; foreach($_POST['t_size'] as $value){ $tshirt_sizes_array[] = $value; } $tshirt_sizes = implode(', ', $tshirt_sizes_array); - Watch for SQL injection: Your use of
IN($t_sizes)works for your current setup, but if$t_sizesever comes directly from untrusted user input, switch to prepared statements to avoid security risks.
内容的提问来源于stack exchange,提问作者Ajinkya More

