J
J
jasonOk2015-11-09 14:07:48
PHP
jasonOk, 2015-11-09 14:07:48

How to organize the right requests?

The question is related to a mysql query.
There is a list of "articles" displayed on the page using while($row = $query -> fetch())
A problem is that you need to display not only the articles themselves, but also

  • the number of comments on them
  • Last commenter login and comment time
  • Author login

For all this, there are separate requests, and in other cases there are even more of them.
Lots of different database queries. And it all looks like this
while($row = $stmt -> fetch()){

$query = $DB->prepare("SELECT `login`,`gender`,`email` FROM `users`  WHERE `id`=:author limit 1");
$query -> bindParam(':author', $row['author']);
$query -> execute();
$T2 = $query -> fetch();

$query = $DB->prepare("SELECT `id`,`time`,`name` FROM `comments`  WHERE `comTo`=:id ORDER BY `id` DESC limit 1");
$query -> bindParam(':id', $row['id']);
$query -> execute();
$T = $query -> fetch();

// Допустим так выводит
echo "Название <a href="site.com/topic/'.$row['id'].'">".$row['name'].'</a>';
echo '<br> Автор <a href="'.$row['author'].'">'.$row[''].'</a>';
// и т.д.

} // end while

The bottom line is that I very much doubt that this is the right thing to do. I heard requests in a cycle to do a sin, and to output like this through echoand even more so ...
The database will be very loaded, right?
Point to the right path!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Talgat Baltasov, 2015-11-09
@talgatbaltasov

read about join

A
Adamos, 2015-11-09
@Adamos

Even without JOIN (you never know, some data can be multi-line) it is absolutely not necessary to fence loops.
You requested articles. Received data. Why withdraw immediately? Collect them for now in an array, along the way creating an array of id articles, authors, what else is needed there.
Next, make one (!) query - SELECT author_name FROM authors WHERE author_id IN (we already have this array). A similar query or two to the table with comments - and that's it, you don't need to pull the database anymore, and all the data for output has been received.
You see, little by little the realization will come of what benefits the separation of logic and conclusion brings ...

S
shagguboy, 2015-11-09
@shagguboy

>the number of comments to them
create a separate field "comments_count" and update it when inserting / deleting a comment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question