Reputation: 35
I have searched for my question but none seems to answer my particular need. It is a simple table join but every thing i have tried has failed. maybe you can help. NOTES: all rows have post_id in POSTS but not all post_ids are related in CALENDAR, ie not all posts have calendar entries. And I am using MYSQL in PHP, not MYSQLi.
POST_CAT- post_id, cat_id POSTS- post_id, title, description CALENDAR- post_id, on_date, to_date
currently i found the relevant post_ids through a many to many selection then used a series of for loops to output from a single table. this works. but i need to include the calendar entries for relevant post_id in one array:
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("adamsmap_db") or die(mysql_error());
if (isset($_POST['activities'])) {
$post_id = mysql_query("SELECT post_id FROM post_cat WHERE cat_id = '1'");
while ($row = mysql_fetch_array($post_id, MYSQL_NUM)) {
for ($i=0;$i < count($row); $i++) {
$output = mysql_query("SELECT user_id, title, description FROM posts WHERE post_id='$row[$i]'");
while ($rowoutput = mysql_fetch_array($output, MYSQL_NUM)) {
for($i=0;$i < count($rowoutput);$i++) {
echo $rowoutput[$i]." ";
}
echo"<br /> <br />";
}}}}
Upvotes: 1
Views: 126
Reputation: 10841
This query will replicate the business logic you've coded and the calendar info:
SELECT
zpc.ost_id, p.user_id, p.title, p.description, c.*
FROM Z_post_cat zpc
INNER JOIN posts p ON zpc.post_id = p.post_id
INNER JOIN calendar c ON c.post_id = = p.post_id
WHERE zpc.cat_id = '1'
If you wish to include categories which do not have posts, use LEFT JOIN instead of INNER JOIN.
Also, it's recommended that you move to PDO or Mysqli instead of mysql due to security concerns.
Upvotes: 1