我在foreach循环中遇到mysqli_query时遇到问题,我首先从表中获取一个字符串,然后将其分成一个数组。然后我尝试循环遍历数组并在循环内调用查询。
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
$row = mysqli_fetch_assoc($langs_result);
$langs = $row['Languages'];
$userLangs = str_replace(" ","",$langs);
$userLangs = explode(",",$langs);
print_r($userLangs);
$posts = array();
foreach($userLangs as $lang){
echo "$lang <br>";
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql);
array_push($posts, mysqli_fetch_assoc($getLangPosts));
}
print_r($posts);
对于这个用户,langusges是德语,意大利语,丹麦语和英语,但$posts
数组只包含从第一语言(德语)找到的第一个帖子,任何人都可以帮忙吗?我正在尝试获取$userLangs
数组中每种语言的所有帖子。
它正好经过foreach
循环,因为每次回显的$lang
变量都会发生变化,但查询仍无法正常工作。
感谢您的帮助!
答案 0 :(得分:1)
select posts.* from posts
left join users on users.language=posts.language
where users.username='your_desiredusername'
group by users.language;
只需尝试通过填写用户名将其作为单个查询运行 无需多次查询
答案 1 :(得分:0)
您需要循环内部查询以获取列数据
foreach($userLangs as $lang){
echo "$lang <br>";
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql);
while($row1 = mysqli_fetch_assoc($getLangPosts))
array_push($posts, $row1['YOUR_COLUMN_NAME']);
}
或者你应该使用IN子句而不是loop
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
while($row = mysqli_fetch_assoc($langs_result)){
$langs = $row['Languages'];
$userLangs = str_replace(" ","",$langs);
$userLangs = explode(",",$langs);
print_r($userLangs);
$posts = array();
$sql = "SELECT * FROM posts WHERE Language IN ('".implode(',',$userLangs)."')";
$getLangPosts = mysqli_query($con, $sql);
while($row1 = mysqli_fetch_assoc($getLangPosts))
array_push($posts, $row1['YOUR_COLUMN_NAME']);
}
答案 2 :(得分:0)
mysqli_fetch_assoc
只在每次调用时获取一行,您需要使用它,如下所示:
while ($row_new = mysqli_fetch_assoc($getLangPosts)){
array_push($posts, $row_new);
}