xPDO

Accessing the Database

gourmet fare

Database Access

Your custom snippet needs to query the site database.

Tontttu asked...

When I had MODx evolution, I used following code to get information from the database:

<?php
  $haku = mysql_query( "SELECT id, pagetitle, parent, description, content FROM `revo_site_content` WHERE `parent`=3 ORDER BY `id` DESC  LIMIT 2");
 
while ( $tiedot = mysql_fetch_array ( $haku ) )
{
 ...
}
?>

When I installed the MODx Revolution, this code doesn’t work anymore. I read that with the Revolution I have to use some ORM or xPDO thing but I have no idea how to use them... And haven’t found anythind easy enough for me. So could you help me with that? How I can get those information from my MySQL database with the Revolution?

The Solution

BobRay says...

Revolution uses xPDO. Here’s an example that should get you started:

<?php
$c = $modx->newQuery('modResource');
$c->select(array('id', 'pagetitle', 'parent', 'description', 'content'));
 
$c->where(array(
   'published'=>'1',
   'deleted'=>'0',
   'parent'=>'3',
));
 
$c->sortby('id', 'DESC');
 
$docs = $modx->getCollection('modResource', $c);
 
foreach ($docs as $doc) {
    $output .= '<br />Title:' . $doc->get('pagetitle') . ' ID:' . $doc->get('id') .'<br />';
}
return $output;  

What's the Story?

As BobRay said, MODX uses xPDO. This is an extension of PHP's PDO abstraction layer, and it uses a different database connection than the standard mysqli_db functions. To use the existing MODX database connection, you must use the xPDO API.

If for some reason you really need to use PHP's mysqli_db functions, you'll have to make a separate mysqli connection to the database.