In PHP website development, it supports various database engines, such as Mysql, Mssql, Pgsql, and sqlite, and provides different functions as interfaces for various database systems, it brings a lot of convenience to PHP website developers.
But it also brings about the platform portability problem. As the underlying database changes, the PHP code must also change. There are various solutions to this problem, such as using the php adodb class, php pear db class, or self-writing the php db class to aggregate function operations of various databases, today we will share with you how to install and use the php pear db class to implement access to different databases.
Preparations
1. before accessing the database using the php pear db class, you need to install the php pear class, and then download and install the DB class through the PEAR install db class.
2. Install related databases as needed, such as Mysql, Mssql, Pgsql, and Sqlite. Find Dynamic Extensions in PHP. INI, introduce the DLL file of the corresponding data, and restart Apache.
Note: Because DedeAMPZ is used, you must install it in the DedeAMPZWebRootDefault directory when installing php pear; otherwise, DB is introduced. failedopening required' DB will be reported during php. the php' error indicates that the DB class (cocould not find pear db library) cannot be found, because DedeAMPZ may limit the related directories.
Php pear db Class Example
- < ?
- require_once("DB.php");
- $userName = 'root';
- $password = '123456';
- $hostName = 'localhost';
- $dbName = 'test';
- $dsn = "mysql://$userName:
$password@$hostName/$dbName";
- $dbCon = DB::connect($dsn);
- if (DB::isError($dbCon)) {
- die ($dbCon->getMessage());
- }
- $sql = "CREATE TABLE leapsoul (".
- "`id` INT( 11 ) UNSIGNED NOT NULL ,".
- "`name` VARCHAR( 30 ) CHARACTER
SET gbk COLLATE gbk_chinese_ci NOT NULL ,".
- "`age` INT( 2 ) NOT NULL ,".
- "`birthday` VARCHAR( 30 ) CHARACTER
SET gbk COLLATE gbk_chinese_ci NOT NULL ,".
- "`sex` INT( 1 ) NOT NULL ,".
- "PRIMARY KEY ( `id` )".
- ") ENGINE = MYISAM CHARACTER SET gbk
COLLATE gbk_chinese_ci";
- $result = $dbCon->query($sql);
- if (DB::isError($result)) {
- die ($result->getMessage());
- }
- $sql = "insert into leapsoul(id,name,
age,birthday,sex) values(1,'leapsoul',1,
'2009-05-13',1),(2,'leapsoul',1,'2009-05
-13',1),(3,'leapsoul',1,'2009-05-13',1)";
- $result = $dbCon->query($sql);
- if (DB::isError($result)) {
- die ($result->getMessage());
- }
- $dbCon->setFetchMode(DB_FETCHMODE_ASSOC);
- $sql = "select * from leapsoul";
- $result = $dbCon->query($sql);
- if (DB::isError($result)) {
- die ($result->getMessage());
- }
- for($i=0;$i<$result->numRows();$i++)
- {
- $info = &$result->fetchRow();
- echo "name:".$info['name'];
- echo "birthday:".$info['birthday']."<br>";
- }
- $result->free();
- $dbCon->disconnect();
- }
The above is the detailed usage of the php pear db class.