我遇到了我的查询问题,它正在检索所有对象两次(除了最后一个)我过去两天一直在尝试排序而没有结果,所以我想我可以问这里。先谢谢你。
PS:
我已经取得了进展,如果我在PHPMYADMIN上执行它,则错误来自查询,数据被检索两次。 (所以有人可以在查询中发现错误)
$token = ***
$userid = ***
$followingposts = $db->query('
SELECT
personal_posts.id,
personal_posts.body,
personal_posts.posted_at,
personal_posts.postimg,
personal_posts.likes,
users.`username`
FROM users, personal_posts, followers
WHERE (
personal_posts.user_id = followers.user_id
OR personal_posts.user_id = :userid
)
AND users.id = personal_posts.user_id
AND follower_id = :userid
ORDER BY personal_posts.posted_at DESC;
', array(':userid'=>$userid), array(':userid'=>$userid));
$response = "[";
foreach($followingposts as $post) {
$response .= "{";
$response .= '"PostId": '.$post['id'].',';
$response .= '"PostBody": "'.$post['body'].'",';
$response .= '"PostedBy": "'.$post['username'].'",';
$response .= '"PostedAt": "'.$post['posted_at'].'",';
$response .= '"PostImage": "'.$post['postimg'].'",';
$response .= '"Likes": '.$post['likes'].'';
$response .= "},";
}
$response = substr($response, 0, strlen($response)-1);
$response .= "]";
http_response_code(200);
echo $response;
class DB {
private $pdo;
public function __construct() {
$pdo = new PDO('****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo = $pdo;
}
public function query($query, $params = array()) {
$statement = $this->pdo->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
return $data;
}
}
}
答案 0 :(得分:0)
(充分部分回答。)
ANSI连接语法将谓词移出where子句,并使它们更接近表引用。 20多年来,这被认为是SQL查询中的最佳实践。是时候停止在from子句中使用逗号了,并明确表格如何连接在一起。 E.g。
SELECT
personal_posts.id,
personal_posts.body,
personal_posts.posted_at,
personal_posts.postimg,
personal_posts.likes,
users.`username`
FROM users
INNER JOIN personal_posts ON users.id = personal_posts.user_id
LEFT OUTER JOIN followers ON personal_posts.user_id = followers.user_id
WHERE personal_posts.user_id = :userid
ORDER BY personal_posts.posted_at DESC;
注意我不确定上述查询是否是确切的替换