Ioannis P.
Ioannis P.

Reputation: 131

Trying to build simple tag system with php

In my database I have a table called topics, in the table there is the tags column where the tags are stored in a comma-separated order (for example $row['tags'] = "tag1,tag2,tag3,...". What I'm trying to do is display related topics depending on the tags that each has. The code below identifies only the single "tag" it finds (for example $row['tags'] ="tag1"). Do you have something to suggest? Thanks in advance.

 <?php
    $result_topic = $conn -> prepare("SELECT * FROM topics WHERE topics.topic_id = :id");
    $result_topic->bindValue(':id',$topic_id, PDO::PARAM_INT);
    $result_topic -> execute();
    while($row = $result_topic->fetch(PDO::FETCH_ASSOC))
    {
$tag = explode(",",$row['tags']);
            for($i = 0; $i < count($tag); $i++){
            $current_tag = $tag[$i];
           $relative_topics = $conn -> prepare("SELECT topic_subject FROM topics WHERE tags LIKE ?");
           $relative_topics -> bindParam(1,$current_tag);
            $relative_topics -> execute();
            $get_relative_topics = $relative_topics -> fetch(PDO::FETCH_ASSOC);
            echo $get_relative_topics['topic_subject'].'<br>';
                                }

       }
?>

Upvotes: 0

Views: 84

Answers (2)

hassan
hassan

Reputation: 8288

Like expression :

With LIKE you can use the following two wildcard characters in the pattern:
% matches any number of characters, even zero characters.
_ matches exactly one character.

so, you need to use the % wildcard in your query:

$current_tag = "%" . $tag[$i] . "%";
$relative_topics = $conn -> prepare("SELECT topic_subject FROM topics WHERE tags LIKE ?");

Upvotes: 1

Vivek Srivastava
Vivek Srivastava

Reputation: 569

You could try using following SQL query -

$relative_topics = $conn -> prepare("SELECT topic_subject FROM topics WHERE tags LIKE %?%");

Upvotes: 0

Related Questions