Within my website, I make use of a tagging system. It works, however I noticed that it's extremely inefficient and needs to perform a separate SQL query for each tag in the event that I would like to display a list of tags.
This is my tag table within the database
This is how tags are fetched and displayed:
$tags = json_decode(json_encode(explode(',', $row["tags"])));
foreach($tags as $tag) {
$fetchTags = $conn->prepare("SELECT id, name FROM tags WHERE id = ? AND type = 1");
$fetchTags->bind_param("i", $tag);
$fetchTags->execute();
$fetchResult = $fetchTags->get_result();
if($fetchResult->num_rows === 0) print('No rows');
while($resultrow = $fetchResult->fetch_assoc()) {
?><span class="badge bg-primary me-2"><?php echo $resultrow["name"]; ?></span><?php
}
$fetchTags->close();
}
Note that the $tags
would be equivalent to their tag ID(s) e.g. 1,2,3
. It may be fine for searching up 1 tag, but you can see the problem when you have 5-10 tags that need searching for.
I was thinking of having the tags being searched within 1 SQL query but the way MySQLi works and binding parameters is odd. I saw some people on here suggest using PDO but I'm not sure of how the implementation would work. I can use PDO instead if needed but ideally I would like to keep using MySQLi.
source https://stackoverflow.com/questions/70032903/is-there-a-better-way-to-display-tags-using-php-mysqli
No comments:
Post a Comment