0

I need help with this please because I can't see a reason why this isn't working.

I have a mysql query which selects all items in ptb_reviews and ptb_profiles tables.

I have set ptb_reviews.from_user_id to be equal to ptb_profiles.user_id so now I am wanting to echo out the display_name of the user_id in ptb_profiles that are equal to the from_user_id in ptb_reviews.

However it won't display the display_name, the only way it works is if I echo out the from_user_id which gives me the user number rather than the name.

My ptb_reviews table looks like this:

id  |  from_user_id  | to_user_id  | content |
1           2               5         hello
2           5               6         hi
3           -1              6         hello 

My 'ptb_profiles' table looks like this:

id  |  user_id  |  display_name  |
1         2            jack
2         5            lisa

Here's my mysql query:

function get_reviews() {
            global $connection;
            global $profile_id;
            $query = "SELECT *
                        FROM ptb_reviews, ptb_profiles
                        WHERE ptb_reviews.to_user_id = \"$profile_id\"
                        AND ptb_reviews.deleted ='0'
                        AND ptb_reviews.approved = '1'
                        AND ptb_reviews.from_user_id = '-1'
                        OR ptb_reviews.from_user_id = ptb_profiles.user_id
                        GROUP BY ptb_reviews.content
                        ORDER BY ptb_reviews.date_added DESC
                        LIMIT 5";
            $reviews_set = mysql_query($query, $connection);
            confirm_query($query, $connection);
            return $reviews_set;
        }

php:

  <?php $reviews_set = get_reviews();
    if(mysql_num_rows($reviews_set) > 0) {
    while ($reviews = mysql_fetch_array($reviews_set)) { ?>

<?php echo "{$reviews['display_name']}"; ?>

Can someone please show me where I'm going wrong because I can't figure it out.

Thanks

4

1 回答 1

0

首先,不要使用“隐式连接”(select * from table1, table2 where table1.aField = table2.aField);使用显式连接:select * from table1 inner join table2 on table1.aField = table2.aField.

我建议一些简单的步骤来确保你得到你想要的。在您的 PHP 项目中实现之前,请尝试在您的 MySQL 控制台(或 Workbench 或其他界面)中执行的所有操作。

使用适当的过滤器返回表中的所有行to_user_id应该很容易。

select 
    *
from
    ptb_reviews as r
    inner join ptb_profiles as p on r.from_user_id = p.userId
where
    r.deleted = '0'
    r.approved = '1'
order by
    r.date_added desc
limit 5

如果可行,则开始添加where您需要的条件。一个一个地尝试它们,当你得到你需要的东西时,把它放在你的 PHP 项目中

于 2013-05-01T19:25:26.933 回答