http://bbs.phppx.com/thread-29-1-1.html
先从一个简单的数据库模式开始。清单 1 所示的模式针对的是单一的数据表数据库,容纳图书列表。
清单 1. MySQL 数据库模式
- DROP TABLE IF EXISTS book;
- CREATE TABLE book (
- book_id INT NOT NULL AUTO_INCREMENT,
- title TEXT,
- publisher TEXT,
- author TEXT,
- PRIMARY KEY( book_id )
- );
请把这个模式装入到名为 bookdb 的数据库。
接下来,编写一个常规的数据库类,然后再把它修改成动态的。清单 2 显示了图书表的简单的数据库访问类。
清单 2. 基本的数据库访问客户机
- <?php
- require_once("DB.php");
- $dsn = 'mysql://root:password@localhost/bookdb';
- $db =& DB::Connect( $dsn, array() );
- if (PEAR::isError($db)) { die($db->getMessage()); }
- class Book
- {
- private $book_id;
- private $title;
- private $author;
- private $publisher;
- function __construct()
- {
- }
- function set_title( $title ) { $this->title = $title; }
- function get_title( ) { return $this->title; }
- function set_author( $author ) { $this->author = $author; }
- function get_author( ) { return $this->author; }
- function set_publisher( $publisher ) {
- $this->publisher = $publisher; }
- function get_publisher( ) { return $this->publisher; }
- function load( $id )
- {
- global $db;
- $res = $db->query( "SELECT * FROM book WHERE book_id=?",
- array( $id ) );
- $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
- $this->book_id = $id;
- $this->title = $row['title'];
- $this->author = $row['author'];
- $this->publisher = $row['publisher'];
- }
- function insert()
- {
- global $db;
- $sth = $db->prepare(
- 'INSERT INTO book ( book_id, title, author, publisher )
- VALUES ( 0, ?, ?, ? )'
- );
- $db->execute( $sth,
- array( $this->title,
- $this->author,
- $this->publisher ) );
- $res = $db->query( "SELECT last_insert_id()" );
- $res->fetchInto( $row );
- return $row[0];
- }
- function update()
- {
- global $db;
- $sth = $db->prepare(
- 'UPDATE book SET title=?, author=?, publisher=?
- WHERE book_id=?'
- );
- $db->execute( $sth,
- array( $this->title,
- $this->author,
- $this->publisher,
- $this->book_id ) );
- }
- function delete()
- {
- global $db;
- $sth = $db->prepare(
- 'DELETE FROM book WHERE book_id=?'
- );
- $db->execute( $sth,
- array( $this->book_id ) );
- }
- function delete_all()
- {
- global $db;
- $sth = $db->prepare( 'DELETE FROM book' );
- $db->execute( $sth );
- }
- }
- $book = new Book();
- $book->delete_all();
- $book->set_title( "PHP Hacks" );
- $book->set_author( "Jack Herrington" );
- $book->set_publisher( "O'Reilly" );
- $id = $book->insert();
- echo ( "New book id = $id/n" );
- $book2 = new Book();
- $book2->load( $id );
- echo( "Title = ".$book2->get_title()."/n" );
- $book2->delete( );
- ?>
为了保持代码简单,我把类和测试代码放在一个文件中。文件首先得到数据库句柄,句柄保存在一个全局变量中。然后定义 Book 类,用私有成员变量代表每个字段。还包含了一套用来从数据库装入、插入、更新和删除行的方法。
底部的测试代码先删除数据库中的所有条目。然后,代码插入一本书,输出新记录的 ID。然后,代码把这本书装入另一个对象并输出书名。
清单 3 显示了在命令行上用 PHP 解释器运行代码的效果。
清单 3. 在命令行运行代码
- % php db1.php
- New book id = 25
- Title = PHP Hacks
- %
不需要看太多,就已经得到重点了。Book 对象代表图书数据表中的行。通过使用上面的字段和方法,可以创建新行、更新行和删除行。