tags:

views:

50

answers:

1

Using PHP and MySQL I'm trying to select unique values from multiple columns in a table (but not all the columns in the table) and put all the unique values from each column selected in its own array. The uniqueness of each columns values should be compared only to other values in the same column.

The code below puts all the unique values from all the columns in the $make_array then puts empty values in all the rest of the arrays.

How can I select only unique values from these columns and put each columns values in its own array?

$sql = "
    (SELECT make FROM items)
    UNION
    (SELECT model FROM items)
    UNION
    (SELECT year FROM items)
    UNION
    (SELECT month FROM items)
    UNION
    (SELECT day FROM items)
    UNION
    (SELECT hour FROM items)";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {

    $make = $row[make];
    $model = $row[model];
    $year = $row[year];
    $month = $row[month];
    $day = $row[day];
    $hour = $row[hour];

    $make_array[make][] = $make;
    $model_array[model][] = $model;
    $year_array[year][] = $year;
    $month_array[month][] = $month;
    $day_array[day][] = $day;
    $hour_array[hour][] = $hour;
}
+1  A: 

If you want to keep it as one SQL statement, then you could:

$sql = "
    SELECT DISTINCT 'make' as descr,make as val FROM items
    UNION
    SELECT DISTINCT 'model' as descr,model as val FROM items
    UNION
    SELECT DISTINCT 'year' as descr,year as val FROM items
    UNION
    SELECT DISTINCT 'month' as descr,month as val FROM items
    UNION
    SELECT DISTINCT 'day' as descr,day as val FROM items
    UNION
    SELECT DISTINCT 'hour' as descr,hour as val FROM items";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
    $make_array[$row['descr']][]=$row['val'];
}
Rudu
@Mark this will do what you were trying to do, though I'm not sure what you were trying to do makes much sense. You're probably just as well off to execute them as separate queries.
bemace
Certainly don't disagree with that @bemace although from Mark's comments perhaps this is just a pseudo-example - perhaps this approach makes more sense for his application.
Rudu