* Licensed under GPL version 2 or later */ global $smarty_block_forsql_results, $sqlconn; /** Stack of sql results (for nested invocations) */ $smarty_block_forsql_results = array(); /** MySQL connection (reused within one page) */ $sqlconn = null; /** * Smarty {forsql}{/forsql} block plugin * * Type: block function
* Name: forsql
* Purpose: iterate over the results of an SQL statement * @param params array *
 * Params:   select: string (the select statement)
 *           item: string (name of the row variable, like foreach)
 * 
* @param content string contents of the block * @param smarty Smarty object * @param repeat whether to call this method again * @return content with row variable set to the current row * @author Willem van Engen */ function smarty_block_forsql($params, $content, &$smarty, &$repeat) { global $smarty_block_forsql_results, $sqlconn; // gather config $select = null; $item = null; foreach ($params as $_key => $_val) { switch ($_key) { case 'select': case 'item': $$_key = (string)$_val; break; default: $smarty->trigger_error("forsql: unknown attribute '$_key'"); } } if ($select==null) $smarty->trigger_error("forsql: require parameter select"); if ($item==null) $smarty->trigger_error("forsql: require parameter item"); // open tag: execute query if (is_null($content)) { if (!$sqlconn) { // TODO make configurable $sqlconn = mysqli_connect($smarty->forsql_host, $smarty->forsql_user, $smarty->forsql_passwd, $smarty->forsql_db); if (!$sqlconn) $smarty->trigger_error("forsql: could not connect to database: ".mysqli_connect_error()); } $result = mysqli_query($sqlconn, $select); if (!$result) $smarty->trigger_error("forsql: query error: ".mysqli_error($sqlconn)); array_unshift($smarty_block_forsql_results, $result); } // get data set row variable for coming block $data = mysqli_fetch_assoc($smarty_block_forsql_results[0]); if ($data) { $smarty->assign($item, $data); $repeat = true; } else { array_shift($smarty_block_forsql_results); $smarty->clear_assign($item); $repeat = false; } return $content; } /* vim:set expandtab ts=4 sw=4: */ ?>