I’m trying to get all the categories about the specific blogpost but it will not work as I wanted it to work. Below you can see the SQL and code. $blog fetch the information about the specific blogpost.
CREATE TABLE IF NOT EXISTS `blogposts` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`id_user_created` int(10) DEFAULT '0',
`id_user_edited` int(10) DEFAULT '0',
`post_subject` varchar(100) NOT NULL,
`post_message` text NOT NULL,
`post_categories` text NOT NULL,
`date_published` datetime NOT NULL,
`date_edited` datetime NOT NULL,
`info_ipaddress_created` text NOT NULL,
`info_ipaddress_edited` text NOT NULL,
`is_shared` enum('0','1') DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`id_user` int(10) DEFAULT '0',
`post_name` text NOT NULL,
`date_added` datetime NOT NULL,
`date_edited` datetime NOT NULL,
`info_ipaddress` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
$get_categories = "SELECT * FROM blogposts, categories
WHERE blogposts.id = '".(int)$blog['id']."'
AND blogposts.post_categories = categories.id
";
foreach($sql->query($get_categories) AS $category) {
echo '<a href="'.url('blog/category/'.$category['post_name']).'" class="grey-link">';
echo $category['post_name'];
echo '</a>';
}
INSERT INTO blogposts` (id, id_user_created, id_user_edited, post_subject, post_message, post_categories, date_published, date_edited, info_ipaddress_created, info_ipaddress_edited, is_shared)
VALUES (1, 1, 1, 'test', 'testar', '1', '', '', '', '', '0'),
(2, 1, 1, 'med kategorier', 'wiho!', '1|2', '', '', '', '', '0');
INSERT INTO categories` (id, id_user, post_name, date_added, date_edited, info_ipaddress)
VALUES (1, 1, 'test', '', '', ''),
(2, 1, 'test2', '', '', '');
Right now it’s only prints Categorized in test, on both blogposts I have posted. It should prints out Categorized in test for the first post and Categorized in test, test2 for the second post. post_categories looks like this: 1|2 which is the ID for the specific category.
Thanks in advance.
If I look at your ‘blogposts’ table, your ‘post_categories’ field is of type text. I don’t know what is in there but I can imagine it to be a string with id’s separated by some character like a semi-colon. This approach limit’s the flexibility of your queryies. You’d be better of by creating a link table. This means that you introduce a new table that is responsible for the linkage between a blogpost and it’s categories. Looking something like:
This last table can be used to get all categories that come with a blogpost. You can query over it by using a JOIN, like so:
You will than have a list with a lot of duplication but each row is for another category which you can use to display somewhere or whatever purpose you have with it. Maybe it is cleaner to separate this into two queries that a. get the blogpost with the id you have and b. get the categories that come with the blogpost by using the link table.