简体   繁体   English

从两个不同的表获取MySQL值到数组中?

[英]Getting MySQL values into an array from two different tables?

My tagging system uses two tables, tags and coupon_tags . 我的标记系统使用两个表tagscoupon_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. 因此,例如,优惠券可以具有ID 13 ,标签可以具有ID 5 coupon_tags makes a new row per coupon per tag, so it may look like so: coupon_tags会为每个标签的每个优惠券添加一个新行,因此看起来像这样:

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 . 在我正在处理的代码中, couponID是已知的,并表示为变量$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). 我需要帮助在以下方面:所以,我必须做的是找出所有地方行couponID是,拉所有这些tagID的到一个数组,例如$allTagIDs[]然后通过循环数组,并在每次迭代时,将tagID与下一个称为tags表中的tagName匹配(两个表都有一个tagID字段,这就是我将它们匹配的方式)。 Those tags need to be put into an array as well. 这些标签也需要放入数组中。

Then for output, I'll just print_r($arrOfTagNames) . 然后,为了输出,我将只用print_r($arrOfTagNames) I just don't know how to do what I wrote up there in PHP. 我只是不知道该怎么做我在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 . 您要编写一个查询,以检索与优惠券$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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