使用PEAR/MDB2开发PHP和MYSQL程序[含Smarty应用]
首先要安装PEAR:
在PHP安装目录下有个PEAR目录下面有个go-pear.phar,在控制台执行命令:
php go-pear.phar
就可以安装PEAR的最新版本包管理器了。
期间会提示修改PHP.INI和在注册表中注册环境变量 (运行PEAR目录下的PEAR_ENV.reg)
PEAR包管理器的常用命令:
pear list
用来显示都安装了哪些软件
pear install MDB2
这个命令就可以自动安装MDB2。
pear install pear/MDB2#mysql
这个命令安装mysql driver。
如果碰到类似:pear/MDB2_Driver_mysql need PHP mysql extensions之类的错误,则要检查一下php.ini中是否将mysql extension打开了:
extension=php_mysql.dll (去掉前面的 ; 号)
罗嗦一句,本来PEAR/DB是比较流行的,现在DB被MDB2替代了。另外,使用PHP直接操作数据库的做法在网站结构上不推荐。还是使用JAVA的后台操作数据库好些,让PHP只做Presentation Layer。
简单PEAR实例:
先在MYSql里面建个表
CONNECT GUESTBOOK;
CREATE TABLE GUESTBOOK (
id int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
EntryDate datetime NOT NULL default '0000-00-00 00:00:00',
Comment varchar(500) NOT NULL default '',
PRIMARY KEY (id),
KEY EntryDate (EntryDate)
) TYPE=MyISAM;
GRANT ALL ON GUESTBOOK.* to guestbook@localhost identified by 'foobar';
CREATE DATABASE GUESTBOOK;
CONNECT GUESTBOOK;
CREATE TABLE GUESTBOOK (
id int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
EntryDate datetime NOT NULL default '0000-00-00 00:00:00',
Comment text NOT NULL,
PRIMARY KEY (id),
KEY EntryDate (EntryDate)
) TYPE=MyISAM;
GRANT ALL ON GUESTBOOK.* to guestbook@localhost identified by 'foobar';
然后写PHP进行调用
创建一个php project,名字叫GuestBook。
在根目录下创建php file:index.php
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: index.php
* Version: 1.0
*/
// define our application directory
define('GUESTBOOK_DIR', 'P:/EclipseWorkspace/GuestBook/');
// define smarty lib directory
define('SMARTY_DIR', 'P:/Smarty/libs/');
// include the setup script
include(GUESTBOOK_DIR . 'libs/guestbook_setup.php');
// create guestbook object
$guestbook =& new Guestbook;
// set the current action
$_action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view';
switch($_action) {
case 'add':
// adding a guestbook entry
$guestbook->displayForm();
break;
case 'submit':
// submitting a guestbook entry
$guestbook->mungeFormData($_POST);
if($guestbook->isValidForm($_POST)) {
$guestbook->addEntry($_POST);
$guestbook->displayBook($guestbook->getEntries());
} else {
$guestbook->displayForm($_POST);
}
break;
case 'view':
default:
// viewing the guestbook
$guestbook->displayBook($guestbook->getEntries());
break;
}
?>
创建目录libs
创建文件libs/guestbook_setup.php
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: guestbook_setup.php
* Version: 1.0
*/
require(GUESTBOOK_DIR . 'libs/sql.lib.php');
require(GUESTBOOK_DIR . 'libs/guestbook.lib.php');
require(SMARTY_DIR . 'Smarty.class.php');
require('MDB2.php'); // PEAR DB
// database configuration
class GuestBook_SQL extends SQL {
function GuestBook_SQL() {
$dsn = array(
'phptype' => 'mysql',
'username' => 'root',
'password' => 'admin',
'hostspec' => 'localhost',
'database' => 'guestbook'
);
// $dsn = "mysql://root:admin@localhost/guestbook";
$this->connect($dsn) || die('could not connect to database');
}
}
// smarty configuration
class Guestbook_Smarty extends Smarty {
function Guestbook_Smarty() {
$this->template_dir = GUESTBOOK_DIR . 'Smarty/templates';
$this->compile_dir = GUESTBOOK_DIR . 'Smarty/templates_c';
$this->config_dir = GUESTBOOK_DIR . 'Smarty/configs';
$this->cache_dir = GUESTBOOK_DIR . 'Smarty/cache';
}
}
?>
创建文件libs/guestbook.lib.php
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: guestbook.lib.php
* Version: 1.0
*/
/**
* guestbook application library
*
*/
class Guestbook {
// database object
var $sql = null;
// smarty template object
var $tpl = null;
// error messages
var $error = null;
/**
* class constructor
*/
function Guestbook() {
// instantiate the sql object
$this->sql =& new GuestBook_SQL;
// instantiate the template object
$this->tpl =& new Guestbook_Smarty;
}
/**
* display the guestbook entry form
*
* @param array $formvars the form variables
*/
function displayForm($formvars = array()) {
// assign the form vars
$this->tpl->assign('post',$formvars);
// assign error message
$this->tpl->assign('error', $this->error);
$this->tpl->display('guestbook_form.tpl');
}
/**
* fix up form data if necessary
*
* @param array $formvars the form variables
*/
function mungeFormData(&$formvars) {
// trim off excess whitespace
$formvars['Name'] = trim($formvars['Name']);
$formvars['Comment'] = trim($formvars['Comment']);
}
/**
* test if form information is valid
*
* @param array $formvars the form variables
*/
function isValidForm($formvars) {
// reset error message
$this->error = null;
// test if "Name" is empty
if(strlen($formvars['Name']) == 0) {
$this->error = 'name_empty';
return false;
}
// test if "Comment" is empty
if(strlen($formvars['Comment']) == 0) {
$this->error = 'comment_empty';
return false;
}
// form passed validation
return true;
}
/**
* add a new guestbook entry
*
* @param array $formvars the form variables
*/
function addEntry($formvars) {
$_query = sprintf(
"insert into GUESTBOOK values(0,'%s',NOW(),'%s')",
mysql_escape_string($formvars['Name']),
mysql_escape_string($formvars['Comment'])
);
return $this->sql->query($_query);
}
/**
* get the guestbook entries
*/
function getEntries() {
$this->sql->query("select * from GUESTBOOK order by EntryDate DESC");
return $this->sql->result;
}
/**
* display the guestbook
*
* @param array $data the guestbook data
*/
function displayBook($data = array()) {
$this->tpl->assign('data', $data);
$this->tpl->display('guestbook.tpl');
}
}
?>
创建文件libs/sql.lib.php
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: sql.lib.php
* Version: 1.0
*/
// define the query types
//define('SQL_NONE', 1);
//define('SQL_ALL', 2);
//define('SQL_INIT', 3);
//
//// define the query formats
//define('SQL_ASSOC', 1);
//define('SQL_INDEX', 2);
class SQL {
var $db = null;
var $result = null;
var $error = null;
var $record = null;
/**
* class constructor
*/
function SQL() { }
/**
* connect to the database
*
* @param string $dsn the data source name
*/
function connect($dsn) {
$this->db = MDB2::factory($dsn);
if(PEAR::isError($this->db)) {
$this->error = $this->db->getMessage();
return false;
}
return true;
}
/**
* query the database
*
* @param string $query the SQL query
* @param string $type the type of query
* @param string $format the query format
*/
function query($query) {
$this->db->setFetchMode(MDB2_FETCHMODE_ASSOC);
MDB2::loadFile('Iterator');
$resultset = $this->db->query($query, true, true, 'MDB2_BufferedIterator');
if (PEAR::isError($resultset)) {
$this->error = $resultset->getMessage();
return false;
}
$this->result = array();
foreach($resultset as $row)
{
$this->result[] = $row;
}
return true;
}
}
?>
创建目录Smarty
创建目录Smarty/cache
创建目录Smarty/configs
创建目录Smarty/templates
创建目录Smarty/templates_c
创建文件Smarty/templates/guestbook_form.tpl
{* Smarty *}
<form action="{$SCRIPT_NAME}?action=submit" method="post">
<table border="1">
{if $error ne ""}
<tr>
<td bgcolor="yellow" colspan="2">
{if $error eq "name_empty"}You must supply a name.
{elseif $error eq "comment_empty"} You must supply a comment.
{/if}
</td>
</tr>
{/if}
<tr>
<td>Name:</td>
<td><input type="text" name="Name" value="{$post.Name|escape}" size="40"></td>
</tr>
<tr>
<td valign="top">Comment:</td>
<td><textarea name="Comment" cols="40" rows="10">{$post.Comment|escape}</textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
创建文件Smarty/templates/guestbook.tpl
{* Smarty *}
<table border="0" width="300">
<tr>
<th colspan="2" bgcolor="#d1d1d1">Guestbook Entries (<a href="{$SCRIPT_NAME}?action=add">add</a>)</th>
</tr>
{foreach from=$data item="entry"}
<tr bgcolor="{cycle values="#dedede,#eeeeee" advance=false}">
<td>{$entry.name|escape}</td>
<td align="right">{$entry.entrydate|date_format:"%e %b, %Y %H:%M:%S"}</td>
</tr>
<tr>
<td colspan="2" bgcolor="{cycle values="#dedede,#eeeeee"}">{$entry.comment|escape}</td>
</tr>
{foreachelse}
<tr>
<td colspan="2">No records</td>
</tr>
{/foreach}
</table>
OK,运行吧,看到类似下面的画面:
这个程序也是Smarty应用的例子。
<?php
/**
* Project: Guestbook Sample Smarty Application
* Author: Monte Ohrt <monte [AT] ohrt [DOT] com>
* Date: March 14th, 2005
* File: guestbook_setup.php
* Version: 1.0
*/
require(GUESTBOOK_DIR . 'libs/sql.lib.php');
require(GUESTBOOK_DIR . 'libs/guestbook.lib.php');
require(SMARTY_DIR . 'Smarty.class.php');
require('MDB2.php'); // PEAR DB
// database configuration
class GuestBook_SQL extends SQL {
function GuestBook_SQL() {
$dsn = array(
'phptype' => 'mysql',
'username' => 'root',
'password' => 'admin',
'hostspec' => 'localhost',
'database' => 'guestbook'
);
// $dsn = "mysql://root:admin@localhost/guestbook";
$this->connect($dsn) || die('could not connect to database');
}
}
// smarty configuration
class Guestbook_Smarty extends Smarty {
function Guestbook_Smarty() {
$this->template_dir = GUESTBOOK_DIR . 'Smarty/templates';
$this->compile_dir = GUESTBOOK_DIR . 'Smarty/templates_c';
$this->config_dir = GUESTBOOK_DIR . 'Smarty/configs';
$this->cache_dir = GUESTBOOK_DIR . 'Smarty/cache';
}
}
?>