PHP還是比較常用的,於是我研究了一下PHP資料庫檔案,在這裡拿出來和大家分享一下,希望對大家有用。我們會看到一個應用程式中,每個表都在一個單獨的資料庫中。在大型資料庫中這樣做是合理的,但是對於一般的應用程式,則不需要這種層級的分割。此外,不能跨資料庫執行關係查詢,這會影響使用關聯式資料庫的整體思想,更不用說跨多個資料庫管理表會更困難了。 那麼,多個資料庫應該是什麼樣的呢?首先,您需要一些資料。清單 1 展示了分成 4 個檔案的這樣的資料。
清單 1. PHP資料庫檔案
- Files.sql:
- CREATE TABLE files (
- id MEDIUMINT,
- user_id MEDIUMINT,
- name TEXT,
- path TEXT
- );
-
- Load_files.sql:
- INSERT INTO files VALUES ( 1, 1, 'test1.jpg', 'files/test1.jpg' );
- INSERT INTO files VALUES ( 2, 1, 'test2.jpg', 'files/test2.jpg' );
-
- Users.sql:
- DROP TABLE IF EXISTS users;
- CREATE TABLE users (
- id MEDIUMINT,
- login TEXT,
- password TEXT
- );
-
- Load_users.sql:
- INSERT INTO users VALUES ( 1, 'jack', 'pass' );
- INSERT INTO users VALUES ( 2, 'jon', 'pass' );
您可以用很多的方式建立資料庫設計、資料庫訪問和基於資料庫的 PHP 商務邏輯代碼,但最終一般以錯誤告終,以及在遇到這些問題時如何修複它們。在這些檔案的多資料庫版本中,您應該將 SQL 陳述式載入到一個資料庫中,然後將 users SQL 陳述式載入到另一個資料庫中。用於在資料庫中查詢與某個特定使用者相關聯的檔案的 PHP 代碼如下所示。get_user 函數串連到包含使用者表的資料庫並檢索給定使用者的 ID。get_files 函數串連到檔案表並檢索與給定使用者相關聯的檔案行。做所有這些事情的一個更好辦法是將資料載入到一個資料庫中,然後執行查詢,比如下面的查詢。
清單 2. PHP資料庫檔案Getfiles.php
- <?php
- require_once("DB.php");
-
- function get_user( $name )
- {
- $dsn = 'mysql://root:password@localhost/bad_multi1';
- $db =& DB::Connect( $dsn, array() );
- if (PEAR::isError($db)) { die($db->getMessage()); }
-
- $res = $db->query( "SELECT id FROM users WHERE login=?",array( $name ) );
- $uid = null;
- while( $res->fetchInto( $row ) ) { $uid = $row[0]; }
-
- return $uid;
- }
-
- function get_files( $name )
- {
- $uid = get_user( $name );
-
- $rows = array();
-
- $dsn = 'mysql://root:password@localhost/bad_multi2';
- $db =& DB::Connect( $dsn, array() );
- if (PEAR::isError($db)) { die($db->getMessage()); }
-
- $res = $db->query( "SELECT * FROM files WHERE user_id=?",array( $uid ) );
- while( $res->fetchInto( $row ) ) { $rows[] = $row; }
- return $rows;
- }
-
- $files = get_files( 'jack' );
-
- var_dump( $files );
- ?>
清單 3. Getfiles_good.php
- <?php
- require_once("DB.php");
-
- function get_files( $name )
- {
- $rows = array();
-
- $dsn = 'mysql://root:password@localhost/good_multi';
- $db =& DB::Connect( $dsn, array() );
- if (PEAR::isError($db)) { die($db->getMessage()); }
-
- $res = $db->query("SELECT files.* FROM users, files WHERE
- users.login=? AND users.id=files.user_id",
- array( $name ) );
- while( $res->fetchInto( $row ) ) { $rows[] = $row; }
-
- return $rows;
- }
-
- $files = get_files( 'jack' );
-
- var_dump( $files );
- ?>
該代碼不僅更短,而且也更容易理解和高效。我們不是執行兩個查詢,而是執行一個查詢。儘管該問題聽起來有些牽強,但是在實踐中我們通常總結出所有的表應該在同一個資料庫中,除非有非常迫不得已的理由。
http://www.bkjia.com/PHPjc/446457.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446457.htmlTechArticlePHP還是比較常用的,於是我研究了一下PHP資料庫檔案,在這裡拿出來和大家分享一下,希望對大家有用。我們會看到一個應用程式中,每個...