草庐IT

php - 查询输出与 if 条件不一致

coder 2023-10-24 原文

我遇到了一个我无法弄清楚的问题。我正在做一个 SELECT 查询来显示用户的 friend 。我正在加入 users、friends 和 profile_img 表以获取用户信息、他们的个人资料图像和 friend 关系。

在 friend 表中,如果friend_onefriend_twostatus 为2,则表示他们是 friend 。这是我的查询正在检查的内容,然后将其他表连接在一起以检索其他数据,例如用户名和图像。

查询似乎工作正常。另一方面,我的输出不是应该的。

在我的 friend 表中,如果您正在查看第 2 行(参见下面的插入),friend_one 是 5,friend_two 是 1。但是,当我尝试输出 friend 列表时,我的查询获取了这两个用户的数据,我只想显示与我正在查看的用户个人资料关联的好友列表。因此,如果我在 friend 1 的个人资料页面上,我要显示的数据仅适用于 friend 5。

CREATE TABLE `friends` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `friend_one` int(11) NOT NULL DEFAULT '0',
 `friend_two` int(11) NOT NULL DEFAULT '0',
 `status` enum('0','1','2') COLLATE utf8_unicode_ci DEFAULT '0',
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`),
 KEY `friend_two` (`friend_two`)
);

INSERT INTO `friends`
VALUES 
(1, 1, 2, 2, NOW()),
(2, 5, 1, 2, NOW())
;

我尝试了一个 if 语句来继续传递与我所在的个人资料用户页面匹配的 friend 数据,它适用于 friend_1 输出...这将显示 1,但它不不要为 friend_imgfriend_username 这样做。

有没有人明白为什么它对 $friend_1 有效,但对他们的其他数据无效?图片和用户名正在输出个人资料用户的数据,这应该是相反的,只是他们的 friend 数据。

    $friend_status = 2;
    $friend_sql = "
    SELECT f.*,
        u1.*,
        u2.*,
        p1.*,
        p2.*,
        IFNULL(p1.img, 'profile_images/default.jpg') AS img1,
        IFNULL(p2.img, 'profile_images/default.jpg') AS img2
    FROM friends f
    LEFT JOIN users u1 ON u1.id = f.friend_one 
    LEFT JOIN users u2 ON u2.id = f.friend_two
    LEFT JOIN (
        SELECT user_id, max(id) as mid
        FROM profile_img
        GROUP BY user_id
    ) max1 ON u1.id = max1.user_id
    LEFT JOIN (
        SELECT user_id, max(id) as mid
        FROM profile_img
        GROUP BY user_id
    ) max2 ON u2.id = max2.user_id
    LEFT JOIN profile_img p1 ON p1.user_id = f.friend_one and p1.id = max1.mid
    LEFT JOIN profile_img p2 ON p2.user_id = f.friend_two and p2.id = max2.mid
    WHERE (friend_one = :profile_user or friend_two = :profile_user)
            AND status = :total_status
    ";
    $friend_stmt = $con->prepare($friend_sql);
    $friend_stmt->execute(array(':profile_user' => $profile_user, ':total_status' => $friend_status));
    $friend_total_rows = $friend_stmt->fetchAll(PDO::FETCH_ASSOC);
    $count_total_friend = $friend_stmt->rowCount();
?>  
            <div id="friend-list-container">
                <div id="friend-list-count">Friends <span class="light-gray"><?php echo $count_total_friend; ?></span></div>
                <div id="friend-list-image-container">
<?php
    foreach ($friend_total_rows as $friend_total_row) {
        $friend_1           = $friend_total_row['friend_one'];
        $friend_2           = $friend_total_row['friend_two'];
        $friend_img_src     = $friend_total_row['img'];
        $friend_img         = '<img src="'.$friend_img_src.'" alt="Friend Image">';
        $friend_username    = $friend_total_row['username'];
        if($friend_1 !== $profile_user) {
            echo '<div class="friend-list-block">
                    <div class="friend-list-block-img">' .
                    $friend_img .
                        '<div class="friend-list-block-details">'. $friend_1 . " "
                    . $friend_username .
                '</div></div></div>';

        }

Fiddle

最佳答案

如果我没有正确理解您的请求,我认为您正在寻找:

SELECT u.*, p.img
FROM users u
LEFT JOIN (
        SELECT user_id, max(id) as mid
        FROM profile_img
        GROUP BY user_id
    ) mid ON u.id = mid.user_id
LEFT JOIN profile_img p ON p.id = mid.mid
WHERE u.id in (
    SELECT friend_one FROM friends WHERE friend_two = 1 AND status = 2
    UNION
    SELECT friend_two FROM friends WHERE friend_one = 1 AND status = 2 
    );

好的,这是 PHP 部分的更新...

<?php
    foreach ($friend_total_rows as $friend_total_row) {
        $friend_id          = $friend_total_row['id'];
        $friend_img_src     = $friend_total_row['img'];
        $friend_img         = (!empty($friend_img_src)) ? '<img src="'.$friend_img_src.'" alt="Friend Image">' : '';
        $friend_username    = $friend_total_row['username'];
            echo '<div class="friend-list-block">
                    <div class="friend-list-block-img">' .
                    $friend_img .
                        '<div class="friend-list-block-details">'. $friend_id . " "
                    . $friend_username .
                '</div></div></div>';

    }

关于php - 查询输出与 if 条件不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873506/

有关php - 查询输出与 if 条件不一致的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby - 如何进行排列以有效地定制输出 - 2

    这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][

  5. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  6. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  9. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  10. ruby - ruby 中有 each_if 吗? - 2

    假设我在Ruby中有这个each循环。@list.each{|i|putsiifi>10breakend}我想循环遍历列表直到满足条件。这让我感到“不像Ruby”,因为我是Ruby的新手,是否有Ruby方法可以做到这一点? 最佳答案 您可以使用Enumerable#detect或Enumerable#take_while,取决于您想要的结果。@list.detect{|i|putsii>10}#Returnsthefirstelementgreaterthan10,ornil.正如其他人所指出的,更好的风格是先进行子选择,然后再对其

随机推荐