|
|
前のページ
1
2 |
|
エラーのハンドリング |
オブジェクトAPIを利用する場合、mysqliクラスを継承して、独自にエラーのハンドリングを行う処理を作成できます。リスト3、リスト4では、各種エラーが発生した場合に例外を発生させてcatch{}ブロックに処理を渡しています。
|
リスト3:child.inc |
<?
class CihildMySQLi extends mysqli
{
function __construct( $Host, $Name, $Pass, $DB )
{
@parent::__construct( $Host, $Name, $Pass, $DB );
if( mysqli_connect_error( ) != "" )
{ throw new Exception ( mysqli_connect_error( ) ); }
}
function prepare( $SQL )
{
$Result = parent::prepare( $SQL );
if( mysqli_error( $this ) != "" )
{ throw new Exception ( mysqli_error( $this ) ); }
return $Result;
}
function query( $SQL )
{
$Result = parent::query( $SQL );
if( mysqli_error( $this ) != "" )
{ throw new Exception ( mysqli_error( $this ) ); }
return $Result;
}
function kill( $ID )
{
$Result = parent::kill( $ID );
if( mysqli_error( $this ) != "" )
{ throw new Exception ( mysqli_error( $this ) ); }
return $Result;
}
}
class ChildStmt
{
function execute( $Object1, $Object2 )
{
$Object2->execute( );
if( mysqli_error( $Object1 ) != "" )
{ throw new Exception ( mysqli_error( $Object1 ) ); }
}
}
?> |
|
リスト4:exception.php |
<?
include( "child.inc" );
try{
$CihildMySQLi = new CihildMySQLi ( "localhost", "root", "", "testdb" );
$Result = $CihildMySQLi->query ( "select now( )" );
print_r( $Result->fetch_array( ) );
$Result = $CihildMySQLi->query ( "select new( )" );
print_r( $Result->fetch_array( ) );
} catch( Exception $Exception ) {
print_r( $Exception->getMessage ( )."\n" );
}
?> |
|
プリペアドクエリとバインド変数(1) |
改良版MySQL拡張サポートでは、プリペアドクエリとバインド変数がネイティブでサポートされています。これを利用すると、引数のみ異なる同一のクエリを複数回行うときに構文解析が1回で済むので、実行効率の向上を期待できます(リスト5)。
|
リスト5:bind.php |
<?
include( "child.inc" );
try{
$ChildMySQLi = new CihildMySQLi( "localhost", "root", "", "testdb" );
$InsertStmt = $ChildMySQLi->prepare( "insert into hoge values( ?, ? )" );
$InsertStmt->bind_param( "is", $No1, $No2 );
for( $XX = 1; $XX <= 5; ++$XX )
{
$No1 = $XX;
$No2 = "test".$XX;
ChildStmt::execute( $ChildMySQLi,$InsertStmt );
}
$Result = $ChildMySQLi->query( "select no1, no2 from hogeorder by no1" );
while( $Array = $Result->fetch_assoc( ) )
{
print_r( $Array );
}
} catch( Exception $Exception ) {
print_r( $Exception->getMessage( )."\n" );
}
?> |
|
前のページ
1
2
|
|
|
|
著者プロフィール
桝形 誠二
様々な言語を経験していく中でPHPと出会い、初心者に易しいという魅力に惹かれ続けて早5年。色んな事をPHPで実装しようとしすぎて周囲の反感を買いやすいのが最近の悩み。
|
|
|
|