Nik Coughin wrote (in part):
Today is the first time I've used MySQL with PHP.
What is the best way to turn a column into an array?
This is how I am doing it at the moment, surely this is sub-optimal:
$query = 'SELECT something FROM table';
$result = mysql_query( $query );
$i = 0;
while( $arrayTemp = mysql_fetch_arr ay( $result ) )
{
$array[ $i++ ] = $arrayTemp[ 0 ];
}
echo "<ul>\n"
foreach( $array as $string )
{
echo "<li>$strin g</li>\n";
}
echo "</ul>\n";
Think about whether you're going to use the information you've
collected more than once. If you are, use an array to store it, if not
use it as soon as you retrieve it.
If you want to store it in an array, you can simplify your code a
little. You don't need the variable $i. Your "while" statement can be
reduced to:
$array = array(); // initialize your array
while ($row = mysql_fetch_ass oc($result))
$array[] = $row['something']; // This is much clearer, especially
if you
// decide to fetch more than one
column.
In your case, since it looks like you're creating a list, you could do
it like this:
echo "<ul>\n";
while ($row = mysql_fetch_ass oc($result))
echo '<li>' . $row['something'] . "<li>\n";
echo "<ul>\n";
Or if you plan to using the generated list in a number of places:
while ($row = mysql_fetch_ass oc($result))
$array[] = '<li>' . $row['something'] . '<li>';
The each place where you want to print the list:
echo "<ul>\n";
echo implode("\n",$a rray[]) . "\n";
echo "</ul>\n";
Ken