Connector.php
データベースとの通信、追加、削除、変更、読み取り(CRUD)を担当します
まず、Connectorクラスを作成し、属性を設定します
<?php class Connector { // 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等 private $driver = 'mysql'; // 数据库地址 private $host = 'localhost'; // 数据库默认名称, 设置为静态是因为有切换数据库的需求 private static $db = 'sakila'; // 数据库用户名 private $username = 'root'; // 数据库密码 private $password = ''; // 当前数据库连接 protected $connection; // 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可 protected static $container = []; // PDO默认属性配置,具体请自行查看文档 protected $options = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; }
上記のコードコメントを見れば理解できるはずです したがって、これ以上の説明はせずに、関数に直接アクセスしてください
-
buildConnectString - DSN接続文字列を生成するためのもので、非常に簡単です
protected function buildConnectString() { return "$this->driver:host=$this->host;dbname=".self::$db; } // "mysql:host=localhost;dbname=sakila;"
-
connect - データベースに接続します
public function connect() { try { // 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中 self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options); // 返回数据库连接 return $this->connection; } catch (Exception $e) { // 若是失败, 返回原因 // 还记得dd()吗?这个辅助函数还会一直用上 dd($e->getMessage()); } }
-
setDatabase - データベースを切り替えます
public function setDatabase($db) { self::$db = $db; return $this; }
-
_construct - インスタンスを生成した後の最初のステップは何ですか?
function construct() { // 如果从未连接过该数据库, 那就新建连接 if(empty(self::$container[self::$db])) $this->connect(); // 反之, 从$container中提取, 无需再次通信 $this->connection = self::$container[self::$db]; }
次の 2 つの関数式は一緒に使用されているので、見て混乱するかもしれません。この例を使用して段階的にデバッグします
$a = new Connector(); $bindValues = [ 'PENELOPE', 'GUINESS' ]; dd($a->read('select * from actor where first_name = ? and last_name = ?', $bindValues));戻り値
array (size=1) 0 => object(stdClass)[4] public 'actor_id' => string '1' (length=1) public 'first_name' => string 'PENELOPE' (length=8) public 'last_name' => string 'GUINESS' (length=7) public 'last_update' => string '2006-02-15 04:34:33' (length=19)
- read - データを読み取ります
public function read($sql, $bindings) { // 将sql语句放入预处理函数 // $sql = select * from actor where first_name = ? and last_name = ? $statement = $this->connection->prepare($sql); // 将附带参数带入pdo实例 // $bindings = ['PENELOPE', 'GUINESS'] $this->bindValues($statement, $bindings); // 执行 $statement->execute(); // 返回所有合法数据, 以Object对象为数据类型 return $statement->fetchAll(PDO::FETCH_OBJ); }
- bindValues - 添付されたパラメータを PDO インスタンスに取り込みます
// 从例子中可以看出, 我用在预处理的变量为?, 这是因为pdo的局限性, 有兴趣可以在评论区讨论这个问题 public function bindValues($statement, $bindings) { // $bindings = ['PENELOPE', 'GUINESS'] // 依次循环每一个参数 foreach ($bindings as $key => $value) { // $key = 0/1 // $value = 'PENELOPE'/'GUINESS' $statement->bindValue( // 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1 // 这里是数值, 因此返回1/2 is_string($key) ? $key : $key + 1, // 直接放入值 // 'PENELOPE'/'GUINESS' $value, // 这里直白不多说 // PDO::PARAM_STR/PDO::PARAM_STR is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } }
_( :3 ∠)
- update - データを書き換える
// 与read不同的地方在于, read返回数据, update返回boolean(true/false) public function update($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
-
// 与update一样, 分开是因为方便日后维护制定 public function delete($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
- create - データを追加する
// 返回最新的自增ID, 如果有 public function create($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); $statement->execute(); return $this->lastInsertId(); }
- lastInsertId -
Addを返すID、
// pdo自带,只是稍微封装 public function lastInsertId() { $id = $this->connection->lastInsertId(); return empty($id) ? null : $id; }
- - 追加、削除、変更
public function exec($sql) { return $this->connection->exec($sql); }
- クエリ - 読み取りに適しています
public function query($sql) { $q = $this->connection->query($sql); return $q->fetchAll(PDO::FETCH_OBJ); }
public function beginTransaction() { $this->connection->beginTransaction(); return $this; } public function rollBack() { $this->connection->rollBack(); return $this; } public function commit() { $this->connection->commit(); return $this; } public function inTransaction() { return $this->connection->inTransaction(); }全コード
<?php class Connector {
// 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等
private $driver = 'mysql';
// 数据库地址
private $host = 'localhost';
// 数据库默认名称, 设置为静态是因为有切换数据库的需求
private static $db = 'sakila';
// 数据库用户名
private $username = 'root';
// 数据库密码
private $password = '';
// 当前数据库连接
protected $connection;
// 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可
protected static $container = [];
// PDO默认属性配置,具体请自行查看文档
protected $options = [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
];
function construct() {
// 如果从未连接过该数据库, 那就新建连接
if(empty(self::$container[self::$db])) $this->connect();
// 反之, 从$container中提取, 无需再次通信
$this->connection = self::$container[self::$db];
}
// 生成DSN连接串
protected function buildConnectString() {
return "$this->driver:host=$this->host;dbname=".self::$db;
}
// 连接数据库
public function connect() {
try {
// 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中
self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options);
// 返回数据库连接
return $this->connection;
} catch (Exception $e) {
// 若是失败, 返回原因
dd($e->getMessage());
}
}
// 切换数据库
public function setDatabase($db) {
self::$db = $db;
return $this;
}
// 读取数据
public function read($sql, $bindings) {
// 将sql语句放入预处理函数
$statement = $this->connection->prepare($sql);
// 将附带参数带入pdo实例
$this->bindValues($statement, $bindings);
// 执行
$statement->execute();
// 返回所有合法数据, 以Object对象为数据类型
return $statement->fetchAll(PDO::FETCH_OBJ);
}
// 将附带参数带入pdo实例
public function bindValues($statement, $bindings) {
// 依次循环每一个参数
foreach ($bindings as $key => $value) {
$statement->bindValue(
// 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1
is_string($key) ? $key : $key + 1,
// 直接放入值
$value,
// 这里直白不多说
is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
);
}
}
// 改写数据
public function update($sql, $bindings) {
// 与read不同的地方在于, read返回数据, update返回boolean(true/false)
$statement = $this->connection->prepare($sql);
$this->bindValues($statement, $bindings);
return $statement->execute();
}
// 删除数据
public function delete($sql, $bindings) {
$statement = $this->connection->prepare($sql);
$this->bindValues($statement, $bindings);
return $statement->execute();
}
// 增加数据
public function create($sql, $bindings) {
$statement = $this->connection->prepare($sql);
$this->bindValues($statement, $bindings);
$statement->execute();
return $this->lastInsertId();
}
// 返回新增id, 如果有
public function lastInsertId() {
$id = $this->connection->lastInsertId();
return empty($id) ? null : $id;
}
// 适用于增删改
public function exec($sql) {
return $this->connection->exec($sql);
}
// 适用于读
public function query($sql) {
$q = $this->connection->query($sql);
return $q->fetchAll(PDO::FETCH_OBJ);
}
public function beginTransaction() {
$this->connection->beginTransaction();
return $this;
}
public function rollBack() {
$this->connection->rollBack();
return $this;
}
public function commit() {
$this->connection->commit();
return $this;
}
public function inTransaction() {
return $this->connection->inTransaction();
}
}
この問題に関する質問1.) PHP 自体、デフォルトではすべてのコード クラスは実行後に自動的に破棄され、PDO は自動的に切断されるため、disconnect() を使用せずに PDO を切断させます。これは悪い習慣なのでしょうか? 2.) 2 つの関数データの追加と書き換えは一度に複数のデータの追加をサポートしておらず、一度にのみデータを追加できます。その理由は、複雑すぎると思う前に書いたので、いくつかの思慮深い子供たちのために削除しました。靴は解決策を提供します
以上が独自のデータベース パッケージを作成する方法 (2)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

MySQLは、初心者がデータベーススキルを学ぶのに適しています。 1.MySQLサーバーとクライアントツールをインストールします。 2。selectなどの基本的なSQLクエリを理解します。 3。マスターデータ操作:テーブルを作成し、データを挿入、更新、削除します。 4.高度なスキルを学ぶ:サブクエリとウィンドウの関数。 5。デバッグと最適化:構文を確認し、インデックスを使用し、選択*を避け、制限を使用します。

MySQLは、テーブル構造とSQLクエリを介して構造化されたデータを効率的に管理し、外部キーを介してテーブル間関係を実装します。 1.テーブルを作成するときにデータ形式と入力を定義します。 2。外部キーを使用して、テーブル間の関係を確立します。 3。インデックス作成とクエリの最適化により、パフォーマンスを改善します。 4.データベースを定期的にバックアップおよび監視して、データのセキュリティとパフォーマンスの最適化を確保します。

MySQLは、Web開発で広く使用されているオープンソースリレーショナルデータベース管理システムです。その重要な機能には、次のものが含まれます。1。さまざまなシナリオに適したInnodbやMyisamなどの複数のストレージエンジンをサポートします。 2。ロードバランスとデータバックアップを容易にするために、マスタースレーブレプリケーション機能を提供します。 3.クエリの最適化とインデックスの使用により、クエリ効率を改善します。

SQLは、MySQLデータベースと対話して、データの追加、削除、変更、検査、データベース設計を実現するために使用されます。 1)SQLは、ステートメントの選択、挿入、更新、削除を介してデータ操作を実行します。 2)データベースの設計と管理に作成、変更、ドロップステートメントを使用します。 3)複雑なクエリとデータ分析は、ビジネス上の意思決定効率を改善するためにSQLを通じて実装されます。

MySQLの基本操作には、データベース、テーブルの作成、およびSQLを使用してデータのCRUD操作を実行することが含まれます。 1.データベースの作成:createdatabasemy_first_db; 2。テーブルの作成:createTableBooks(idintauto_incrementprimarykey、titlevarchary(100)notnull、authorvarchar(100)notnull、published_yearint); 3.データの挿入:InsertIntoBooks(タイトル、著者、公開_year)VA

WebアプリケーションにおけるMySQLの主な役割は、データを保存および管理することです。 1.MYSQLは、ユーザー情報、製品カタログ、トランザクションレコード、その他のデータを効率的に処理します。 2。SQLクエリを介して、開発者はデータベースから情報を抽出して動的なコンテンツを生成できます。 3.MYSQLは、クライアントサーバーモデルに基づいて機能し、許容可能なクエリ速度を確保します。

MySQLデータベースを構築する手順には次のものがあります。1。データベースとテーブルの作成、2。データの挿入、および3。クエリを実行します。まず、createdAtabaseおよびcreateTableステートメントを使用してデータベースとテーブルを作成し、InsertINTOステートメントを使用してデータを挿入し、最後にSelectステートメントを使用してデータを照会します。

MySQLは、使いやすく強力であるため、初心者に適しています。 1.MYSQLはリレーショナルデータベースであり、CRUD操作にSQLを使用します。 2。インストールは簡単で、ルートユーザーのパスワードを構成する必要があります。 3.挿入、更新、削除、および選択してデータ操作を実行します。 4. Orderby、Where and Joinは複雑なクエリに使用できます。 5.デバッグでは、構文をチェックし、説明を使用してクエリを分析する必要があります。 6.最適化の提案には、インデックスの使用、適切なデータ型の選択、優れたプログラミング習慣が含まれます。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

Dreamweaver Mac版
ビジュアル Web 開発ツール

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

WebStorm Mac版
便利なJavaScript開発ツール
