Reputation: 103
after many hints here I tried it to combine the following two querys. I think the code is self explaining.
the tables:
comments: id(INT), username(VARCHAR), autorpost(TEXT), comment(TEXT), id_post(INT), time(TIME)
posts: id(INT), autorid(INT), autor(TEXT), date(DATE), longitude(FLOAT), latitude(FLOAT), title(TEXT), text(TEXT), town(TEXT), time(TIME)
$hostname='localhost';
$user='root';
$password='';
$useron = $_COOKIE['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id_post
FROM comments
WHERE username = '$useron'
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($own = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$ownco = $own->fetchAll(PDO::FETCH_COLUMN, 0);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id, autorid, autor, date, longitude, latitude, title, text, town, time
FROM posts
WHERE id in (" . implode(",",$ownco) . ")
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($resco = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$resultcom = $resco->fetchAll();
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
My own try:
"SELECT posts.id, posts.autorid, posts.autor, posts.date, posts.longitude, posts.latitude, posts.title, posts.text, posts.town, posts.time, comments.id_post
FROM posts
INNER JOIN
comments
WHERE id = post_id
ORDER BY id DESC"
Upvotes: 0
Views: 52
Reputation: 2153
Try this query
"SELECT p.*, c.id_post
FROM posts p
JOIN comments c ON( c.id_post = p.id)
ORDER BY p.id DESC"
Upvotes: 2