I am very new to php and mysql. I am trying to learn as I go and am stuck on this issue.
I have a many-to-many relationship. The tables are: users and state. Many companies in the users table operate in many states and each state has many different companies. Each company on the user table has a unique id that is stored on the state table. The state table then has a column for the state name that the company operates in. A new row is created in the state table for each state the company is in. That all seems to work ok.
I wrote the following php code to pull all the company id’s from the state table for any given state ($state) and then display all the company names (pulled from the users table with the company id) that operate in the given state.
My problem is that I would like to order the list alphabetically of companies that operate in any given state. This code will not do that. Can anyone offer a better way to do this that will allow the list to be ordered (or that will just generally be more efficient and better)?
$state=$_GET['state'];
echo $state;
$aid=array();
$result=mysql_query("SELECT * FROM state WHERE state='$state'");
while($row=mysql_fetch_assoc($result)){
$v=$row['company_id'];
array_push($aid,$v);};
foreach($aid as $val){
$result1=mysql_query("SELECT * FROM users WHERE company_id='$val'");
$row1=mysql_fetch_assoc($result1);
$company=$row1['company'];
echo $company.'<br/>';};
The table structures are:
users
company_id
company
(other columns that are not relevant)
state
index
company_id
state
(no additional columns)
Try this SQL statement:
This should give you an alphabetic list of companies per state selected. The ORDER BY uses the state first in case you decide to expand your query to get more than one states.