I'm trying to get my head around doing related links. So I have a link which going to a page called post.php and displays the correct post from the database. Now I want to echo out all the titles (with their links) in a different div where the category is equal to that post?
For example the post I'm displaying is the first record in the table. It should display all the titles with category 1. If however I'm displaying a page which is category 2, then will also display other titles with category 2.
Code I have echoing out the page to post.php:
<?php
require_once("db/db.php");
$sql = $db->prepare("
SELECT *
FROM mytable
WHERE slug=?
");
$sql->bind_param("s",$_GET["slug"]);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
}
?>
<h2><?php echo $row['mytitle'];?></h2>
<?php echo $row['mypost'];?>
+----+-----------------------------+-------------------------------+----------+------------------------+
| id | mytitle | mypost | category | slug |
+----+-----------------------------+-------------------------------+----------+------------------------+
| 1 | title of apost cat1 | it amet, sollicitudin euismod | 1 | my-first-post |
+----+-----------------------------+-------------------------------+----------+------------------------+
| 2 | post of title cat1 | quam tempor mauris elem | 1 | post-of-title |
+----+-----------------------------+-------------------------------+----------+------------------------+
| 3 | Fun title Cat2 | verra mollis justo eget ti | 2 | fun-title |
+----+-----------------------------+-------------------------------+----------+------------------------+
| 4 | What about another one Cat2 | et consequat tortor et vive | 2 | what-about-another-one |
+----+-----------------------------+-------------------------------+----------+------------------------+
You can try this
SELECT t1.mytitle,
t1.mypost,
t2.titles
FROM mytable AS t1
INNER JOIN
(SELECT group_concat(mytitle) AS titles,
category
FROM mytable
GROUP BY category) AS t2 ON t1.category=t2.category
WHERE t1.id=1
Where titles are all the titles that is related to that specific post category.
You can get the current post category by $row['category']
and run the related query:
$sql = $db->prepare("
SELECT *
FROM mytable
WHERE category=? AND id NOT IN (?)
LIMIT 5
");
$sql->bind_param("i",$row['category']);
$sql->bind_param("i",$row['id']);
and than loop the results in separated div. I think that doing this by ajax call is best.