We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 52857
    • 8 Posts
    Hello,

    I've been reading the documentation and I have learned that it is not best practice to output html from a snippet. Can you help identify best practice for this scenario?

    I have a snippet that queries a MySQL database on my server. It finds the 10 latest db entries (they happen to be news headlines), and outputs the list. My first thought is that I should change the echo line to '$output =', and then call that $output on my page. Is that correct? If so, I know how to call the snippet, but how do I print the $output variable on my page?

    Thanks for your help. Loving modx.

    <?php
    include "/path/to/dblogin/details.php";
    $db = new mysqli('localhost', $username, $password, $database);
    
    if($db->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
    }
    
    $sql = <<<SQL
        SELECT *
        FROM `database_16`
        WHERE `col_11` = 'Include'
    ORDER BY submission_id DESC LIMIT 10 
    SQL;
    
    if(!$result = $db->query($sql)){
        die('There was an error running the query [' . $db->error . ']');
    }
    
    while($row = mysqli_fetch_array($result))
      {
     echo "<a href=\"/news-template/full.php?id=". $row['submission_id'] . "\">" . $row['col_5'] . "</a><br /><br />";
      }
    
    $db->close();


    This question has been answered by BobRay. See the first response.

    • discuss.answer
      • 3749
      • 24,544 Posts
      Just return $output in the snippet. The value returned will replace the snippet tag on the page.

      while($row = mysqli_fetch_array($result))
        {
       $output = "<a href=\"/news-template/full.php?id=". $row['submission_id'] . "\">" . $row['col_5'] . "</a><br /><br />";
        }
       
      $db->close();
      
      return $output;

        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 52857
        • 8 Posts
        Ok, that makes sense. Thank you!

        Alex

        Quote from: BobRay at Oct 14, 2016, 07:06 AM
        Just return $output in the snippet. The value returned will replace the snippet tag on the page.

        while($row = mysqli_fetch_array($result))
          {
         $output = "<a href="\"/news-template/full.php?id="." $row['submission_id']="" .="" "\"="">" . $row['col_5'] . "</a>
        
        ";
          }
         
        $db->close();
        
        return $output;