简体   繁体   中英

Getting MySQL values into an array from two different tables?

My tagging system uses two tables, tags and coupon_tags . The way it works is that each coupon and each tag is assigned a numerical value. So a coupon may have the id 13 and a tag may have the id 5 , for example. coupon_tags makes a new row per coupon per tag, so it may look like so:

couponID | tagID
    5        3
    5        1
    5        9
    6        1

In the code I am working on, the couponID is known, and represented as the variable $coupID . I need help on the following: So what I would have to do is figure out all of the rows where couponID is, and pull all of those tagID 's into an array, for example, $allTagIDs[] , and then loop through that array and at each iteration, match the tagID to a tagName in the next table called tags (both tables have a tagID field, which is how I match them up). Those tags need to be put into an array as well.

Then for output, I'll just print_r($arrOfTagNames) . I just don't know how to do what I wrote up there in PHP.

You don't actually want to do that. You want to write ONE query which retrieves the names of the tags associated with coupon $coupID .

If you're ever running a query in a loop, you're probably doing something wrong, and it'll come back to bite you by overloading your server as soon as you have some significant traffic.

$sql = "
    SELECT
      tags.tagID,
      tags.tagName
    FROM
      tags
    INNER JOIN
      coupon_tags
    ON
      coupon_tags.tagID = tags.tagID
    WHERE
      coupon_tags.couponID = $coupID
";

$result = mysql_query($sql);

$arrOfTagNames = array();
while ($row = mysql_fetch_array($result)) {
  $arrOfTagNames[] = $row['tagName'];
}

print_r($arrOfTagNames);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM