Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I would like to tell you about the problem I have to see if someone can help me.
I have created a table in a database with the following columns:

Table: union
exercise_id_fk	tag_id_fk
   1	             1
   1	             2
   2	             1
   2	             3
What I pretend with my program is that a user chooses the tags they want so that the exercise corresponding to the chosen tags is shown on the screen. For example, if the user chooses tag 1, exercises 1 and 2 will appear. If you choose tags 1 and 3, exercises 1 and 2 appear.

The problem with my program is that when the user chooses tags 1 and 3, for example, exercises 1 and 2 appear but 2 repeats. Or when you choosing tags 1 and 2, exercise 1 is repeated.

Does anybody know any way so that this does not happen? Only show the exercises once?

What I have tried:

Here I show part of my code:
PHP
$sql = "SELECT * FROM exercises, union, tags where exercise_id = exercise_id_fk and tag_id = tag_id_fk";

if (!empty($_SESSION['tags_array'])) {
    $sql .= " and (";
    foreach ($_SESSION['tags_array'] as $tagId)
        $sql .= 'tag_id = ' . $tagId . ' or ';

    $sql .= "tag_id = -1);";
}

$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
    echo $row["exercise_id"] . ". " .  $row["title"] . "<br>";
}
Posted
Updated 2-Aug-18 1:06am
v5

1 solution

What you are looking for is the SQL DISTINCT keyword which returns only distinct (different) values.

Also your SQL command is much too complicated (contains redundant information). As far as I understand, you want to query the single table 'union' for a single field. Then the general syntax might be
SQL
SELECT DISTINCT exercise_id_fk FROM union WHERE tag_id_fk IN (<list_of_tags>)
The above uses also the SQL IN keyword to match values from a list.

Untested example from scratch:
PHP
$tags_array = $_SESSION['tags_array'];
$tags = count($tags_array);
$sql = "SELECT DISTINCT exercise_id_fk FROM 'union' WHERE tag_id_fk"; 
if ($tags == 1) {
    $sql .= "=" . $tags_array[0]; 
}
else {
    $sql .= " IN (" . $tags_array[0];
    for ($i = 1; $i < $tags; $i++) {
        $sql .= ", " . $tags_array[$i];
    }
    $sql .= ")"
}
Note that I have quoted the table name 'union' because it is a reserved SQL word.
 
Share this answer
 
Comments
Member 13933133 3-Aug-18 6:25am    
Thank you very much! :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900