We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 51362
    • 4 Posts
    Hi you all,

    I'm not a php expert so there is a big chance there is a mistake in the code avoiding me to be able to get more than one snippet at the time in a template. The website just don't load. Here are the codes of both snippets I'm trying to get. I thing it might be related to the fact that php code in snippets don't allow me to actually close it "?>" and crashes when it is open again... but not sure. I've tried to add it but when I click on "sake" it gets stripped.

    Snippet #1

    <?php
    try {
    		$conexion = new PDO('mysql:host=tanukilibros.com;dbname=tanukili_tanuki;charset=utf8', 'username', 'password');
    
    } catch (PDOException $e) {
    echo "ERROR: " . $e->getMessage();
    die;
    }
    


    Snippet #2

    <?php
    $booksInfo = $conexion->prepare(
    "SELECT libros.Titulo, autores.nombres, autores.apellidos, libros.cubierta, libros.link
    FROM libros
    INNER JOIN autores ON
    libros.Autor = autores.ID
    ORDER BY libros.ID DESC LIMIT 4;"
    );
    $booksInfo->execute();
    $booksInfo = $booksInfo->fetchAll ();


    Thank you in advance for your help!!!

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

    • discuss.answer
      • 3749
      • 24,544 Posts
      You need to either make this a single snippet or re-initialize your $conexion variable in the second snippet. Variable values are not carried across from one snippet to another, even if they're on the same page. There's almost always a way to make two snippets into one snippet.

      For example, if these were the two snippets:
      [[snippet1]]
      [[snippet2]]
      

      /* Snippet1 */
      $x = 'hello';


      /* Snippet2 */
      return 'Value of x is ' . $x;


      What would appear on the page is:

      Value of x is 


      You can definitely have more than one snippet in your template, though, as long as the two are independent, or pass information through an external source like a $_SESSION variable, file, or DB storage.

      The closing PHP tag is optional and is not used in MODX because it can crash pages under certain circumstances. MODX automatically removes it for you.

      Also, some general tips:

      1. Don't use echo or print in a snippet. Instead, create a variable (usually called $output) and return it. The returned value will replace the snippet tag. If there is sometimes output and sometimes not, initialize with $output = ''; at the top of the snippet,change its value if you want output, and return it at the end.

      2. Try to design your snippets so they only have one return statement that comes at the end. I do violate this principle on occasion, but code that follows it is usually a lot easier to maintain.

      2. Don't use die(). Always have a return statement, even if you have nothing to display.

      3. I've never seen a try/catch block in a snippet. I'm not sure if they work reliably. Usually, you test to see if things are OK. If not, you either return an error message --

      return 'Unable to make DB connection in snippet1';


      or write an error to the MODX error log --

      $modx->log(modX::LOG_LEVEL_ERROR, 'Unable to make db connection in snippet1';
      


      In your specific case, the connection won't throw an error unless PDO::ERRMODE_EXCEPTION is set.

      You could try this with the try/catch block:
      $conexion = new PDO('mysql:host=tanukilibros.com;dbname=tanukili_tanuki;charset=utf8', 'username', 'password');
      $conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


      or this might work, without try/catch:

      $conexion = new PDO('mysql:host=tanukilibros.com;dbname=tanukili_tanuki;charset=utf8', 'username', 'password');
      if (!$conexion) {
         /* connection failed */
      }



        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
        • 20413
        • 2,877 Posts
        Awesome post by Bob Ray!

        I place my MODX core folder above public root and store external database connections in scripts like this:
        /core/external/

        https://docs.modx.com/revolution/2.x/administering-your-site/security/hardening-modx-revolution#HardeningMODXRevolution-core

        Then in snippet I can use:
        include($modx->getOption('core_path')."external/database.class.php");
        


        Great PDO method: https://www.culttt.com/2012/10/01/roll-your-own-pdo-php-class/
          @hawproductions | http://mrhaw.com/

          Infograph: MODX Advanced Install in 7 steps:
          http://forums.modx.com/thread/96954/infograph-modx-advanced-install-in-7-steps

          Recap: Portland, OR (PDX) MODX CMS Meetup, Oct 6, 2015. US Bancorp Tower
          http://mrhaw.com/modx_portland_oregon_pdx_modx_cms_meetup_oct_2015_us_bancorp_tower
          • 3749
          • 24,544 Posts
          Brilliant!
            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