We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 15566
    • 73 Posts
    I have this:

    $q = "SELECT * FROM modx_site_content WHERE parent='9' AND deleted!='1' AND published='1' ORDER BY menuindex ASC";
    $query = new xPDOCriteria($modx, $q); 
    if ($query->stmt && $query->stmt->execute()){
    while($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['pagetitle'];
    }
    }


    But how can I get num_rows()? I have tried a wide range of things but nothing has worked.
      • 21257 MODX Staff
      • 730 Posts
      This should work
      $modx->getCount('modResource', $query);
      

        Mike Schell
        Lead Developer, MODX Cloud
        Email: [email protected]
        GitHub: https://github.com/netProphET/
        Twitter: @mkschell
        • 15566
        • 73 Posts
        Strangely, although that looks like it works it’s actually return 156 rather than 5.

        I assume it is bringing back the total number of resources not just the quantity in the query.

        ~~ UPDATE ~~

        This works ok:
        $query->stmt->rowCount();
          • 22303 MODX Staff
          • 10,725 Posts
          It’s much better to use the API here:
          <?php
          // use the API to build the query
          $q = array(
              'parent' => 9,
              'deleted' => false,
              'published' => true
          );
          $query = $modx->newQuery('modResource', $q);
          $query->sortby('menuindex', 'ASC');
          
          // get the distinct modResource rows that would be selected by this query
          // NOTE: this is typically more useful with limit() usage
          $numRows = $modx->getCount('modResource', $query);
          
          // you can use xPDO::getCollection() or xPDO::getIterator() here
          // to fetch the rows as objects, take advantage of caching, etc.
          $iterator = $modx->getIterator('modResource', $query);
          foreach ($iterator as $resource) {
              echo $resource->get('pagetitle');
          }
          


          This will be increasingly important for backwards compatibility as we progress forward and the table structures start to change, cross-platform compatibility, and for taking better advantage of advanced features like result set caching.