简体   繁体   中英

How to opimize / merge this pdo query and this count query?

This code works perfectly well but i would like to know if there is a way to optimize it.

I make a request with PDO and with a foreach loop and i show all my articles stored in database.

$allDatasAgenda = $bdd->query('SELECT id, cat_id, text, img FROM site_agenda 
                                WHERE activation = 1 
                                ORDER BY date_publication')->fetchAll(PDO::FETCH_ASSOC);

<?php 
    $i=1; 
    foreach($allDatasAgenda AS $data_agenda): 

        // generate all html

    endforeach; 
    reset($allDatasAgenda); 
 ?>

For some reasons, I need to know how many articles are stored in database (i need to add a class to the last one in order to make my next / prev jquery function works).

so, i make this :

$countArticlesAgenda = $bdd->query('SELECT count(*) FROM site_agenda WHERE activation = 1');
$count_articles_agenda = $countArticlesAgenda->fetchColumn();

I would like to know if there is a way to have this result with only one query?

It's just a question of optimization and beauty.

If someone can suggest a better title to my question, you're welcome.

To let you know, $allDatasAgenda is array.
To get the number of array elements PHP has a function called - surprise! - count()

For optimizations:

  • Add indexes on the database You should have an index on the activation column at least, but you require a sorted result on date_publication , so an index on (activation,date_publication) would be really usefull.
  • Avoid showing all the content of a database on an html page. What will happend when you will have more than 1000 rows in site_agenda ? Counting the result array is a nice trick but if usually programs perfroms count query and detail result queries it is because they use LIMIT and OFFSET on the result queries to paginate the data. Paginating the data means to avoid showing more than 50 rows to the user, but also to avoid loosing time, memory and bandwith by retrieving more than 50 rows from the database (50 is an example, but nobody wants to read 1000 rows in an html page). So finally you will certainly need a count query to know how many rows you have and you should not get all theses rows on your result.

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