以下は私がこれまでに出てきたdb接続クラスですが、PDOクラス自体を拡張することでそれを改善するつもりです。
<?php
class database
{
protected $connection = null;
#make a connection
public function __construct($hostname,$dbname,$username,$password)
{
try
{
# MySQL with PDO_MYSQL
$this->connection = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$this->connection = null;
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = $this->connection->prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
?>
拡張クラス、
class database extends PDO
{
#make a connection
public function __construct($hostname,$dbname,$username,$password)
{
parent::__construct($hostname,$dbname,$username,$password);
try
{
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
die($e->getMessage());
}
}
#get the number of rows in a result
public function num_rows($query)
{
# create a prepared statement
$stmt = parent::prepare($query);
if($stmt)
{
# execute query
$stmt->execute();
return $stmt->rowCount();
}
else
{
return self::get_error();
}
}
#display error
public function get_error()
{
$this->connection->errorInfo();
}
# closes the database connection when object is destroyed.
public function __destruct()
{
$this->connection = null;
}
}
これが私がクラスをインスタンス化する方法です、
# the host used to access DB
define('DB_HOST', 'localhost');
# the username used to access DB
define('DB_USER', 'root');
# the password for the username
define('DB_PASS', 'xxx');
# the name of your databse
define('DB_NAME', 'db_2011');
include 'class_database.php';
$connection = new database(DB_HOST,DB_NAME,DB_USER,DB_PASS);
$sql = "
SELECT *
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
$connection->num_rows($sql);
しかし、この拡張pdoクラスを呼び出すと、エラーが発生します。
警告:PDO :: __construct()は、パラメーター4が配列であり、文字列がxx行のC:\ wamp \ www \ xx\class_database.phpで指定されていることを想定しています。
致命的なエラー:行xxのC:\ wamp \ www \ xx \ class_database.phpの非オブジェクトでメンバー関数setAttribute()を呼び出す
私はオンラインでいくつかの調査をしました、私はpdoを拡張するこの基本的な構造を見つけました、しかし私はそれを理解していません...
class myPDO extends PDO
{
public function __construct($dsn,
$username=null,
$password=null,
$driver_options=null)
{
parent::__construct($dsn, $username, $password, $driver_options);
}
public function query($query)
{
$result = parent::query($query);
// do other stuff you want to do here, then...
return($result);
}
}
$dsn変数は何のためにありますか?$hostname変数を拡張pdoクラスに渡すにはどうすればよいですか?
別の質問:拡張pdoクラスでエラーを表示するためのメソッドを作成するにはどうすればよいですか?拡張pdoクラスの接続を閉じるにはどうすればよいですか?
mysqliからpdoに移行するのはとても難しいです!
ありがとう。