【问题标题】:Selecting posts id's from Array of user id's - mysql从用户ID的数组中选择帖子ID - mysql
【发布时间】:2017-05-21 02:39:55
【问题描述】:

我有一个我关注的 id 数组 如果我回显:

echo json_encode($followingIds);

打印:

[{"User_two_id":"3"},{"User_two_id":"4"},{"User_two_id":"5"}]

我现在想从 Post 表中选择所有 id,其中 Author 的值等于我的数组中的 User_two_id 的值。

“作者正在索引 user_two 的 id”

这是我到目前为止无法正常工作的地方

function getPosts( $follwingIds ) {

        $sql = "SELECT id
        FROM posts
        WHERE Author IN ('$follwingIds')
        GROUP BY id
        HAVING COUNT(DISTINCT Author)";

    $result = $this->conn->query( $sql );

    if ( $result != null ) {

        while ( $row = $result->fetch_assoc() ) {
            $returnArray[] = $row;
        }
    }




}

【问题讨论】:

  • 数组从何而来?

标签: php mysql sql arrays mysqli


【解决方案1】:

这里有一个问题:

WHERE Author IN ('$follwingIds')

这里 $follwingIdsJSON object 中,其中 mysql IN 需要逗号分隔值中的值。因此,不要将 json 数组转换为字符串,例如:

$follwIds = implode(',', array_column($follwingIds, 'User_two_id'));

并在查询中使用它:

WHERE Author IN ($follwIds)

【讨论】:

  • 谢谢,但是由于某种原因它返回 null。就像它永远不会通过if ( $result != null ) { 我回应了 $follwIds 并且它看起来很好(3,4,5),我什至在 phpmyadmin 中进行了手动查询并将 WHERE Author IN (3,4,5) .. 它给了我想要的但由于某种原因它在 php 中不起作用!
  • 你的函数没有返回任何值可能是这个原因
  • 谢谢,但它不应该在函数中传递 if 语句吗? if ( $result != null ) { echo "notnull"; ..
  • 你是说执行没有进入If部分?
  • 不,它没有通过 if,因为 $result 看起来是空的?我的查询中是否缺少某些内容?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
相关资源
最近更新 更多