1

I currently display some database content through PHP code written directly in the body of several nodes.

I would like to shift this code into node.tpl.php (as I have seen from the Zen examples that code to modify a node should be in node.tpl.php). However, I have multiple nodes, each displaying different kinds of database content.

How should I structure the code in node.tpl.php so that if it is Page A, then I display database content A and if it is Page B, then display database content B?

As an example.

Currently I have the following in one of my node body:

<?php
  $db = mysql_connect('localhost', 'root', '');
  mysql_select_db('sage', $db);
  $query = "show tables";
  $db_query = mysql_query($query, $db);
  echo "<TABLE border = '1'>";
  echo "<TR>";
  echo "<TH>TABLE NAME</TH>";
  echo "</TR>";
  while($row = mysql_fetch_array($db_query)) {
      $tableName = $row[0];
      echo "<TR>";
      echo "<TD><a href=/node/5/$tableName>$tableName</a></TD>";
      echo "</TR>";
  }  
  echo "</TABLE>";
?>

Do I copy and paste this code directly into node.tpl.php?

2
  • I hope this is meant as a joke, this approach of thinking is way of compared to how it can be done and the functionalities provided by Drupal - I encourage you to take a look at the documentation pages especially the Module developer's guide part. further more once you have read about that take a look at API documentation
    – lslinnet
    Commented Mar 22, 2012 at 9:39
  • You are also bypassing Drupal's database abstraction layer by using mysql_connect(), etc., which can be detrimental to both security and performance. You should consult the API documentation for the proper functions to use when connecting to the database.
    – sheena_d
    Commented Mar 22, 2012 at 13:15

2 Answers 2

1

This code DOESN'T belong in the template files. You should implement a module for your business logic, database connection and the like.

Template files should be reserved for theming, or very basic alternatives.

Your case is 'by the book' where it is important to separate logic from presentation, otherwise, as you already understood, you'll end up with duplicate code everywhere, poor performance and an unmaintainable site.

2

I don't See any node id in your code. If all you want is to have PHP generated output for an URL, define the path with hook_ menu() and just return the generated HTML from the call back method.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.