I'm very new to Drupal and I apologize if this is a very elementary question but I have looked around and can't seem to find much discussion about my problem. If there is already please let me know...

I am trying to access the database on a page I created using the PHP code input format. I would like to retrieve the contents of a particular table I created and populated (using PHPMyAdmin) in the database. The tutorial I'm following uses a seperate PHP file containing the username, password, and database information and securely accesses it with PHP INCLUDE() (causing errors BTW). However, it seems that using Drupal this may be unnecessary and that I should use db_query instead of mysql_query.

It will probably be easiest if I show the code that I am trying to use. It creates an XML document containing the results of the query and prints it on the screen... I don't think that this will work with Drupal (or needs to be done). Can anyone help me translate this PHP into something that works with Drupal? This would be a big help in increasing my understanding of the Drupal framework...


<?php

require("phpsqlajax_dbinfo.php");

// Start XML file, create parent node
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("markers");
$parnode = $doc->append_child($node);

// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  $node = $doc->create_element("marker");
  $newnode = $parnode->append_child($node);

  $newnode->set_attribute("name", $row['name']);
  $newnode->set_attribute("address", $row['address']);
  $newnode->set_attribute("lat", $row['lat']);
  $newnode->set_attribute("lng", $row['lng']);
  $newnode->set_attribute("type", $row['type']);
}

$xmlfile = $doc->dump_mem();
echo $xmlfile;

?>

Comments

martinwatson’s picture

Martin Watson (newbie)
Hi, I'm not sure exactly which tutorial you are following, but I'm going to guess it isn't one related specifically to Drupal. Try going to the handbooks page, and then to the module developer's guide and following the tutorials there. These will show you how to access the database etc from within the Drupal framework.

hth