drayarms Posted July 22, 2011 Share Posted July 22, 2011 Hello all, I'm trying to display the contents of a mysql select query in a particular format. So basically, the result of the query returns 3 rows with values, red, white, and blue. I want to display these result in a single string in the following format: 'red', 'white', 'blue' So I use this code in an attempt to achieve that: $query = "SELECT * FROM table WHERE id = 'someNumber' "; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)){ $colors = " ' ".$row['color']." ' " . "," ; echo $colors; $col = substr($colors, 0, -1); echo $col; } So the idea is to wrap each of the row values(red white and blue) within single quotes and separate them with commas. Then I try to trim the last comma after the last entry, in this case blue to get my expected result. As expected the $colors variable reads: 'red', 'white', 'blue', But the $col variable reads: 'red' 'white' 'blue' instead of the expected 'red', 'white', 'blue' So the substr() function instead of just removing the last comma from the $colors string, removes the the last comma from each of the components of that string. Now I thought that PHP would treat $colors as just one string but apparently, that's not the case. How I can make it so? Can anyone tell me what to do next? Every other string trimming function I tried yielded the same undesirable result. Thanks. Quote Link to comment Share on other sites More sharing options...
ScotDiddle Posted July 22, 2011 Share Posted July 22, 2011 drayarms, You could try something similar to the following... Scot L. Diddle, Richmond VA <?php /** * * Simulate multiple SQL queries * */ $array1 = array('red', 'white', 'blue'); $array2 = array('yellow', 'orange', 'purple'); $array3 = array('pink', 'plum', 'violet'); $array = array($array1, $array2, $array3); foreach ($array as $arrayOfColors) { // Simulate SQL Query results $stringOut = ''; foreach ($arrayOfColors as $colors) { $stringOut .= "'" . $colors . "', "; } $strLength = strlen($stringOut); $last = $strLength - 2; $cols = substr($stringOut,0, $last); echo $cols . '<br />'; } /** * * Output: * */ // 'red', 'white', 'blue' // 'yellow', 'orange', 'purple' // 'pink', 'plum', 'violet' ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.