my first plugin! :)
| From: | Rasmus Schultz | Date: | Tue, 04 Jun 2002 23:02:04 +0000 |
| Subject: | my first plugin! :) | ||
| Groups: | php.smarty.general | ||
| Request: | Send a blank email to php-smarty-general+get-4586@lists.php.net to get a copy of this message | ||
Hi,
Below is a copy of my first plugin - it appears to work, but I'd
appreciate some feedback ... I've only been programming PHP for
about two weeks now, and I'm new to Smarty, so I've probably
f*cked something up? :) ... so please, don't post on the contribs
page just yet ...
The following short example template did seem to work fine:
{config_load file="mysql.conf"}
{mysql query="SELECT news_id, date, headline, simpletext, linked FROM news"
var=news host=#host# db=#db# user=#user# pass=#pass# count=4}
<TABLE>
{section name=news loop=$news}
<TR><TD><TD><B>{$news[news][1]|date_format:"%m.%d.%Y"}</B><BR>{$news[news][2
]}</TD></TR>
{/section}
</TABLE>
Note that for efficiency reasons, it doesn't use associative arrays.
Looking in the compiled code, I can see that the result of calling
my plugin function is NOT actually cached ... can somebody tell me
how I might make it cache the results? for example so that the
database would only be queryed every once an hour or so, otherwise
it would just display the cached results - is that possible?
And now, here's the plugin code:
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.mysql.php
* Type: function
* Name: mysql
* Version: 0.1
* Date: June 5th, 2002
* Purpose: Run a query on a MySQL database
* Input: query = a MySQL query
* var = variable to assign result to (optional)
* count = max. number of records to return (optional)
* host = MySQL server hostname (or IP address)
* db = MySQL database name
* user = MySQL username
* pass = MySQL password
* Author: Rasmus Schultz <mindplay(at)mindplay.dk>
* -------------------------------------------------------------
*/
function smarty_function_mysql($params, &$smarty)
{
extract($params);
if (empty($query)) {
$smarty->trigger_error("mysql: missing 'query' parameter");
return;
}
if (empty($host)) {
$smarty->trigger_error("mysql: missing 'host' parameter");
return;
}
if (empty($db)) {
$smarty->trigger_error("mysql: missing 'db' parameter");
return;
}
if (empty($user)) {
$smarty->trigger_error("mysql: missing 'user' parameter");
return;
}
if (empty($pass)) {
$smarty->trigger_error("mysql: missing 'pass' parameter");
return;
}
// Connect to the MySQL database
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if (empty($var)) {
// Just query
mysql_query($query);
} else {
// Query and return result
$result = mysql_query($query);
$c = 0;
if (empty($count)) { $count = -1; }
$a = null;
while (($data = mysql_fetch_row($result)) and (($c<$count) or
($count==-1))) {
$a[] = $data;
$c += 1;
}
$smarty->assign($var, $a);
}
mysql_close();
}
?>