DB query and Placeholders

From MODx Wiki

Jump to: navigation, search


Custom table snippet with custom placeholders .

Custom Table, Custom Placeholders

To access a custom table you have in your MODx database from a snippet and use some custom placeholders to render the output. Create a new snippet to call on your page:

<?php
$output = '';//create variable for holding the output
$sql = $modx->db->query( 'SELECT * FROM `tblprojects` LIMIT 0, 1000');//define the DB query, in this case the table is named 'tblprojects', add WHERE AND etc. as needed
$resultArray = $modx->db->makeArray( $sql );//put it into an array
foreach($resultArray as $item)//go through each record in the array
{//start looping through the data array
$params['award']=$item['Grant_Award'];//set the placeholders, the $params sets the name of the placeholder, the $item is the field name from the DB table
$params['ref']=$item['Project_Ref'];
$params['area']=$item['LA_Area'];
$output.=$modx->parseChunk('ProjectTpl', $params, '[+', '+]');//define the chunk name and process the content, here it's ProjectTpl which has the placeholders for the data
}//finish looping through the data array
return $output;//now return the output from the processed chunk
?>

Here is the ProjectTpl chunk referred to in the snippet:

<h3>[+ref+]</h3>
<p> [+award+]<br>
[+area+]</p>

Based on an example from Bogdan Guenther

--Bunk58 03:47, 1 June 2008 (PDT)

Personal tools