Cole
Cole

Reputation: 459

Joining multiple tables in mySQL

Okay, I'm not that good at mySQL. What I'm trying to do here is join 2 tables: 1. users 2. comments I'm trying to make a comment system where it should pull the username and profile picture from users table and the comments and date_posted from the comments table.

Here is my query:

$mem_query = mysql_query("SELECT `comments`.`comment_id` AS `comments_id`, `users`.`user_id` AS `users_id`, `users`.`username`,`users`.`profile_pic`,`comments`.`txt_content`,`comments`.`date_posted` FROM `comments` INNER JOIN `users` ON `users`.`user_id` = `comments`.`user_id` WHERE `comments`.`post_id` = '$post_id'");

And I want to run the query using the while loop:

while($run_mem = mysql_fetch_array($mem_query)){
    $comment_id = $run_mem['comments_id'];
    $txt_content = $run_mem['comments.txt_content'];
    $profile_pic = $run_mem['users.profile_pic'];

?>
    //Run all the comments depending upon the post_id.
<?php
        }
?>

As of now, it is giving me this error: - THIS IS NOT SHOWING AFTER my 2nd update.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\simpleblog\view.php on line 73

How do I fix it? Thanks.

P.S: I know 'mysql_query' is being deprecated in PHP. I'll change that later. P.S 2: I fixed the query from table.column to table.column, however, its not showing any errors but its not pulling any information from the database.

Upvotes: 1

Views: 87

Answers (3)

ITroubs
ITroubs

Reputation: 11215

there is a big syntax error in your query:

SELECT `comments.comment_id` AS `comments_id`, `users.user_id` AS `users_id`, `users.username`,`users.profile_pic`,`comments.txt_content`,`comments.date_posted` FROM `comments` INNER JOIN `users` ON `users.user_id` = `comments.user_id` WHERE `comments.post_id` = '$post_id'

should be

SELECT `comments`.`comment_id` AS `comments_id`, `users`.`user_id` AS `users_id`, `users`.`username`,`users`.`profile_pic`,`comments`.`txt_content`,`comments`.`date_posted` FROM `comments` INNER JOIN `users` ON `users`.`user_id` = `comments`.`user_id` WHERE `comments`.`post_id` = '$post_id'

you wrote this: `comments.user_id` but it has to be this: `comments`.`user_id` and that at almost every position where you did that wrong

Upvotes: 2

Look at the ` symbols, they should look like:

`table`.`column`

and not:

`table.column`

Upvotes: 3

flup
flup

Reputation: 27104

http://www.php.net/manual/en/function.mysql-query.php

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

Looks like the latter happened. An error occurred and the mysql_query call returned false.

Upvotes: 0

Related Questions