-1

I have some data on my database:

id_tag | tag
------------
1      | Dog
2      | Cat
3      | Buldog
4      | Persian Cat

Then i have a parameter:

$tag = "2, 4";

I want to show All of tags into checkbox. If the id_tag is equal the $tag parameter. I have a trials:

echo "<div class='btn-group' data-toggle='buttons'>";
$thetag = explode(", ", $tag);
$tagall = mysql_query("SELECT * FROM tags");
if(mysql_num_rows($tagall) > 0)
{
    while($tagt = mysql_fetch_array($tagall))
    {
        foreach($thetag as $ttg)
        {
            if($tagt['id_tags'] == $ttg)
            {
                $aktiv = "active";
                $ceked = "checked";
            }
            else
            {
                $aktiv = "";
                $ceked = "";
            }
        }
        echo "<label class='btn btn-primary {$aktiv}'><input type='checkbox' value='{$tagt['id_tags']}' autocomplete='off' {$ceked}> {$tagt['tag']}</label>";
    }
}
echo "</div>";

The result is:

Dog | Cat | Buldog | Persian Cat

with Persian Cat active and checked.

The result i need is Cat and Persian Cat active and checked. Please help me...!

auastyle
  • 3
  • 3

2 Answers2

0

Of course it is, because what you're doing here is looping through $tag inside the main loop pointlessly and each time you rewrite the previously stored information so only the last one is used.

Here's one of the solutions:

while($tagt = mysql_fetch_array($tagall))
    {
         if(in_array($tagt['id_tag'], $thetag))
            {
                $aktiv = "active";
                $ceked = "checked";
            }
            else
            {
                $aktiv = "";
                $ceked = "";
            }
        echo "<label class='btn btn-primary {$aktiv}'><input type='checkbox' value='{$tagt['id_tag']}' autocomplete='off' {$ceked}> {$tagt['tag']}</label>";
    }

In addition, please consider avoiding mysql_* functions.

Community
  • 1
  • 1
fiedlr
  • 106
  • 5
  • woow... I was not imagine about the in_array. I just focused about the foreach. Thanks guys. You are awesome. – auastyle Oct 15 '15 at 23:00
0

The problem is that your foreach ($thetag as $ttg) loop keeps looping after it finds a match. If the next iteration doesn't match, it sets $aktiv and $ceked back to empty strings. The final value of these variables is just based on whether $tagt['id_tags'] matches the last element of $thetag, not whether it matches any of them. You can solve this by putting break after you set $ceked = "checked";.

But a simpler way is with:

if (in_array($tagt['id_tags'], $thetag)) {
    $aktiv = "active";
    $ceked = "checked";
} else {
    $aktiv = "";
    $ceked = "checked";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612