简体   繁体   English

PHP While循环可搜索多个MySQL查询

[英]PHP While loop to search through multiple MySQL queries

I am trying to loop through a searched tag and gather all posts related to that tag. 我试图遍历搜索到的标签并收集与该标签相关的所有帖子。 For that I know I will need to either use the while or foreach loop. 为此,我知道我将需要使用whileforeach循环。

The variable is gathered by: $tag = trim($_GET['tag']); 该变量通过以下方式收集: $tag = trim($_GET['tag']);

Then, I am going to search through the tags table like so: 然后,我将像这样通过标签表进行搜索:

  $stmt = $mysqli->prepare('SELECT post_id FROM tags WHERE tag = ?');
  $stmt->bind_param('s', $tag);
  $stmt->execute();
  $stmt->bind_result($post_id);
  $stmt->store_result();
  $rows = $stmt->num_rows;
  $stmt->fetch();
  $stmt->close();

This will likely return multiple rows as it is searching through all the posts that have a tag, for example 'trips'. 在搜索所有带有标签的帖子(例如“行程”)时,这很可能会返回多行

Then, after gathering the post_id of the relevant tagged posts, I search the posts table to get all the information about the post before outputting it to the user: 然后,在收集了相关标记帖子的post_id之后,我搜索了帖子表以获取有关该帖子的所有信息,然后再将其输出给用户:

  $stmt = $mysqli->prepare('SELECT title FROM posts WHERE id = ?');
  $stmt->bind_param('i', $post_id);
  $stmt->execute();
  $stmt->bind_result($title);
  $stmt->store_result();
  $rows_posts = $stmt->num_rows;
  $stmt->fetch();
  $stmt->close();

My problem is this only will work for one post and I am not sure how to loop this search through so multiple posts with the same tag are returned. 我的问题是,这仅适用于一篇文章,而且我不确定如何循环搜索,因此返回具有相同标签的多篇文章。

You could join the posts table in the first query. 您可以在第一个查询中加入posts表。

SELECT posts.title FROM tags
JOIN posts ON posts.id = tags.post_id
WHERE tag = ?

You can use: foreach($stmt->get_result() as $row) {} then. 您可以使用: foreach($stmt->get_result() as $row) {}

please learn how mysql join works http://dev.mysql.com/doc/refman/5.0/en/join.html In your example the right query would be: 请了解mysql join的工作原理http://dev.mysql.com/doc/refman/5.0/en/join.html在您的示例中,正确的查询为:

SELECT posts.title FROM tags join posts on posts.id = tags.post_id where tag = ?

you dont need to connect the data in php anymore then. 您不再需要在php中连接数据了。

Why not using 为什么不使用

SELECT title FROM posts P INNER JOIN tags T ON P.id = T.post_id WHERE tag = ?

This will result al titles for the specified tag 这将导致指定标签的标题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM