简体   繁体   中英

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.

The variable is gathered by: $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:

  $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.

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.

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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