Friday, June 18, 2010

Adding PHP snippets through the Drupal user interface

Enable PHP input filter: Go to Administer -> Site building -> Modules, and check PHP Filter under core - optional. Now when create new content, a PHP option will appear under input formats - select this to paste a PHP code snippet. This opens a powerful door to creating dynamic content on a Drupal site.

See Drupal: A beginner's guide to using snippets.

Often a PHP snippet is written inside a drupal module block. What if you want to access Drupal database from an external PHP file? Below is an example. See here for reference.

<?php
// Root path of drupal site, can be obtained using getcwd().
$path = "/web/1/www.hawaii.edu/drupalc/";
chdir($path);

// include needed files
include_once('includes/bootstrap.inc');
include_once('includes/database.inc');
//include_once('includes/database.mysql.inc'); // Disable this for drupal 6.

// Launch drupal start: configuration and database bootstrap
conf_init();
drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

// Page start. Output page as an Excel file download.
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"excel_download.xls\"");
header("Pragma: no-cache");
header("Expires: 0");

// table header
echo "<table border='1'>";
db_query("SELECT * FROM users"); // access to database.
// more processing ...
echo "</table>";

?>

No comments:

Blog Archive

Followers