Question

So I have db table>"schools" and a column in this table named "metro". In "metro" i have strings like that "Station Name 1, Station Name 2, Station-Name 5"

I'm doing now a search form with select metro stations, so my code look like this:

<select name="categoryID">
<? 

$metro_sql=mysql_query("SELECT metro FROM schools");
while($metro=mysql_fetch_array($metro_sql)){
    $metro_pieces = explode(", ", $metro['metro']);
        foreach (array_unique($metro_pieces, SORT_REGULAR) as $metro_all) {
             echo "<option value=\"".$metro_all."\">".$metro_all."</option>\n  ";
    }
}

And the result: Metro Station 1 Metro Station 2 Metro Station 3 Metro Station 1 Metro Station 4 Metro Station 5 etc. What I'm doing wrong? p.s. sorry for my english.

Was it helpful?

Solution

I would suggest a better database design.

CREATE TABLE school (
  school_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255)
);

CREATE TABLE station (
  station_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255)
);

CREATE TABLE metro (
  school_id INT NOT NULL,
  station_id INT NOT NULL,
  UNIQUE INDEX (school_id, station_id)
);

You create schools in school and stations in station. When you need to link a school to a station, you add a record to metro. This makes the database normalized.

When you then need to get the stations, you simply do a:

SELECT station.* 
FROM metro
INNER JOIN station
ON metro.station_id = station.station_id
WHERE metro.school_id = $school_id

OTHER TIPS

There is a logical problem.
Strictly speaking you cannot say that "array_unique doesn't work".
Just because there are a dozen other functions involved.
And you have no idea if this function is provided with correct data.

You have to learn to debug your code.
Add debugging output to your code and verify every variable's state to see if it contains desired data.

start from var_dump($metro); inside of the loop

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top