根据两个表中的变量是否匹配来切换语句

时间:2013-04-18 23:44:32

标签: php mysql

所以我有一个switch语句,我希望根据一个表中的id是否在另一个表中具有匹配的外键来显示一种或另一种形式。

到目前为止,我所尝试的是将一个while语句嵌入到另一个不能正常工作的语句中。

$subresult = mysqli_query($con,"SELECT * FROM tags GROUP BY tag");
$subresult2 = mysqli_query($con,"SELECT * FROM tag_subscribe WHERE uid = $uid");

while ($row = mysqli_fetch_array($subresult)) {
    $tid = $row['tid'];

    while ($row2 = mysqli_fetch_array($subresult2)) {
        $tid2 = $row2['tid'];
    }
    if ($tid2 == $tid) {
        $subbedup = 'yes';
    } else {
        $subbedup = 'no';
    }

    switch ($subbedup) {
    case ('yes'):
        echo "alternate html form goes here because $tid2 == $tid";
        break;
    case ('no'):
        echo "html form goes here";
        break;
    }
}

所以当这个代码运行时,它只返回switch" no"除了它将返回一个开关"是"这恰好是包含外键的第二个表的最后一条记录。当我考虑它时,这是有道理的,因为它将继续运行此循环,直到它用完表中的记录。所以我花了大约六分钟来达到这一点,我花了最后6个小时试图让它正常工作,没有任何运气。

再一次,SO的好人,救我!请和谢谢你:)

所以我的问题是:如何才能正确完成?

3 个答案:

答案 0 :(得分:4)

我不确定你的数据库结构,所以我会即兴发挥。

给出这些样本表和列:

tags
id name

tag_subscriptions
user_id tag_id

以下查询将遍历所有标记。每个标记都包含subscribed列设置为“是”或“否”,具体取决于当前用户是否订阅了该特定标记。

$sql="SELECT t.`id`, t.`name`, IF (ISNULL(ts.`tag_id`),'no','yes') AS `subscribed`
  FROM `tags` t
  LEFT JOIN `tag_subscriptions` ts ON (ts.`user_id`=$uid AND ts.`tag_id`=t.`id`)
  WHERE 1;"

然后遍历所有标签:

$q=mysql_query($sql) or die(mysql_error());

while ($row=mysql_fetch_assoc($q)) {
    switch ($row['subscribed']) {
      case 'yes'
        // user is subscribed to this tag
        break;
      default:
        // user is not subscribed to this tag
    }
}

我认为(希望)这更接近你正在寻找的东西。

http://sqlfiddle.com/#!2/58684/1/0

答案 1 :(得分:2)

很抱歉使用PDO就是我所知道的,你可以将这个想法转换为MYSQLi。

$db = new PDO($hostname,$username,$password);

$arraySubTags = array();

$query = "SELECT tagID FROM tag_subscribe WHERE uid = :uid";
$statement = $db->prepare($query);
$statement->bindValue(':uid', $uid);
$statement->execute();
$subscribedTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();

foreach($subscribedTags as $sTag)
{
    array_push($arraySubTags,$sTag);
}

$query = "SELECT * FROM tags GROUP BY tag";
$statement = $db->prepare($query);
$statement->execute();
$allTags = $statement->fetchAll(PDO::FETCH_ASSOC); //or loop with a while using fetch()
$statement->closeCursor();

foreach($allTags as $tag)
{
    if(in_array($tag['tagID'], $arraySubTags))
    {
        echo "person is subscribed";
    }else{ echo "person not subscribed";}
}

答案 2 :(得分:0)

这段代码只检查是否订阅了最后一个标签 - 检查每个你需要将switch语句移动到外部while循环中的if..else位为当前设置$ subbedup变量标签

或者,如果由于某种原因需要将交换机分开,可以将$ subbedup设为一个数组,由标记id索引。

相关问题