我正在尝试从数据库中检索多行。我遇到的问题是每次我使用这个函数时,它都会替换我已经尝试返回的所有其他行,并且它只返回最后一行。如果有人知道更好的方法或知道如何实际完成这项工作,请发表评论。
刚在这里发帖,如果这在某些方面不正确,我们深表歉意。谢谢。
我的代码:
public function getPosts($id){
global $pdo;
$query = $pdo->prepare("SELECT * FROM friends WHERE f1 = ? OR f2 = ?");
$query->bindValue(1, $id);
$query->bindValue(2, $id);
$query->execute();
$res = $query->fetchAll();
foreach($res as $user):
if($user['f1'] == $id):
$query = $pdo->prepare("SELECT * FROM posts JOIN users ON posts.user_id = users.id WHERE user_id = ?");
$query->bindValue(1, $user['f2']);
$query->execute();
else:
$query = $pdo->prepare("SELECT * FROM posts JOIN users ON posts.user_id = users.id WHERE user_id = ?");
$query->bindValue(1, $user['f1']);
$query->execute();
endif;
return $query->fetchAll(); //Trying to return arrays.
endforeach;
}
最佳答案
尝试这样的事情。我不知道 f1 和 f2 是什么,所以我只是将它们添加为占位符。我在这里没有使用bindValue。仅使用 array($f1_id, $f2_id)
调用执行更简单
public function getPosts($id){
global $pdo;
$f1_id = 1; //placeholder
$f2_id = 2; //placeholder
$posts = array();
$stmt = $pdo->prepare("SELECT * FROM friends WHERE f1 = ? OR f2 = ?");
$stmt->execute(array($f1_id, $f2_id));
//Iterate over the friend records.
//fetch() returns next record or false on failure (No more records).
//false terminates the while loop.
while($user = $stmt->fetch()) {
if($user->f1 == $f1_id) :
$stmt_post = $pdo->prepare("SELECT * FROM posts JOIN users ON posts.user_id = users.id WHERE user_id = ?");
$stmt_post->execute(array($user['f2']));
else:
$stmt_post = $pdo->prepare("SELECT * FROM posts JOIN users ON posts.user_id = users.id WHERE user_id = ?");
$stmt_post->execute(array($user->['f1']));
endif;
while($post = $stmt_post->fetch()) {
$posts[] = $post; //"$posts[] = " syntax is used to append the $post to the array.
}
}
return $posts;
}
关于php - 在 PHP 中使用 fetchAll 返回多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22418428/