We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 37475
    • 25 Posts
    I am completely new to xpdo so I'm sorry if it's a stupid question.

    I try to capture only one value in my database. I have solved it using the code below, but realizes that it must be possible to solve without foreach. But how?
    The value in alias is always unique and I just want the id back.

    $output = '';
    
    $query = $modx->newQuery('Product');
    $query->select($modx->getSelectColumns('Product','Product','',array('id')));
    $query->where(array(
       'alias' => 'PRODUCT-NAME',
    ));
    $products = $modx->getCollection('Product',$query);
    
    foreach ($products as $product) {
      
      $output = $product->get('id');
      
    }
    
    return $output;
    
    [ed. note: bingojoviken last edited this post 14 years, 9 months ago.]
      • 22303 MODX Staff
      • 10,725 Posts
      Here is one way, using the new getValue() method...

      <?php
      $output = '';
       
      $query = $modx->newQuery('Product');
      $query->select($modx->getSelectColumns('Product','Product','',array('id')));
      $query->where(array(
         'alias' => 'PRODUCT-NAME',
      ));
      
      $output = $modx->getValue($query->prepare());
      
      return $output;
      
        • 37475
        • 25 Posts
        Fungerar perfekt. Tack.
          • 22303 MODX Staff
          • 10,725 Posts
          Du är hjärtligt välkommen!
            • 37475
            • 25 Posts
            Oops, sorry about the Swedish. Was probably too tired.

            How do I change it if I want both id and title?

            First:

            $query->select($modx->getSelectColumns('Product','Product','',array('id', 'title')));


            Then?
              • 22303 MODX Staff
              • 10,725 Posts
              Easy way:
              <?php
              $product = $modx->getObject('Product', array('alias' => 'PRODUCT-NAME'));
              return $product ? implode('-', $product->get(array('id', 'pagetitle'))) : 'Nothing was retrieved!';
              


              Uses less memory (doesn't load the object):
              <?php
              $output = '';
                
              $query = $modx->newQuery('Product');
              $query->select($modx->getSelectColumns('Product','Product','',array('id', 'pagetitle')));
              $query->where(array(
                 'alias' => 'PRODUCT-NAME',
              ));
              if ($query->prepare() && $query->stmt->execute()) {
                  $row = $query->stmt->fetch(PDO::FETCH_ASSOC);
                  $output = "{$row['id']}, {$row['pagetitle']}";
                  $query->stmt->closeCursor();
              }
               
              return $output;
              
                • 37475
                • 25 Posts
                Thank you again.