Jump to content

[SOLVED] Selecting data from 2 tables with data-checking loop


markkanning

Recommended Posts

Hey ya'll,

I've got a MySQL select-query-with-loop problem. I'm putting together a database-driven, "store locator" page for a wholesale foods outlet. The page will have a list of the 50 states that's being created from one table, AND that will be linked depending on whether corresponding store data for that state actually exists in another table. I'm figuring the query might look something like...

select states.stateid, states.statename, stores.stateid from states, stores where states.stateid = stores.stateid

...but I'm not sure as I'm stumped as to how the following loop will work.

 

I'm guessing the loop may be something like...

for ($i=0; $i <$num_results; $i++) {
$row = mysql_fetch_array($result);
   if (no corresponding table data for this state) {
      echo $statename."<br>\n";
   }
   else {
      echo "<a href=\"?stateid=".$stateid."\">$statename."</a><br>\n";
   }
}

 

Am I on the right track?

 

 

Link to comment
Share on other sites

Your where clause is only going to pull states that have stores. If you want to list states that do not have stores, you need to use the LEFT JOIN syntax, which will include every state and give you NULL store data when a state is without store.

Link to comment
Share on other sites

If you say where states.stateid = stores.stateid, you're only going to get states that have stores.

If you say FROM states LEFT JOIN stores ON states.stateid = stores.stateid, you're going to get all the states, even if they don't have stores.

 

Both of these statements join the tables; only the data they return differs. See this example.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.