1
|
$dbh = new PDO( 'mysql:host=localhost;dbname=test' , $user , $pass ); |
1
2
3
4
5
6
7
8
9
10
|
try { $dbh = new PDO( 'mysql:host=localhost;dbname=test' , $user , $pass ); foreach ( $dbh ->query( 'SELECT * from FOO' ) as $row ) { print_r( $row ); } $dbh = null; } catch (PDOException $e ) { print "Error!: " . $e ->getMessage() . "<br/>" ; die (); } |
1
|
$dbh = null; |
1
2
3
|
$dbh = new PDO( 'mysql:host=localhost;dbname=test' , $user , $pass , array ( PDO::ATTR_PERSISTENT => true )); |
1
|
PDO::beginTransaction() |
1
|
PDO::commit() |
1
|
PDO::rollBack() |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
try { $dbh = new PDO( 'odbc:SAMPLE' , 'db2inst1' , 'ibmdb2' , array (PDO::ATTR_PERSISTENT => true)); echo "Connected\n" ; } catch (Exception $e ) { die ( "Unable to connect: " . $e ->getMessage()); } try { $dbh ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh ->beginTransaction(); $dbh -> exec ( "insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')" ); $dbh -> exec ("insert into salarychange (id, amount, changedate) values (23, 50000, NOW())"); $dbh ->commit(); } catch (Exception $e ) { $dbh ->rollBack(); echo "Failed: " . $e ->getMessage(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
$stmt = $dbh ->prepare( "INSERT INTO REGISTRY (name, value) VALUES (:name, :value)" ); $stmt ->bindParam( ':name' , $name ); $stmt ->bindParam( ':value' , $value ); // 插入一行 $name = 'one' ; $value = 1; $stmt ->execute(); // 用不同的值插入另一行 $name = 'two' ; $value = 2; $stmt ->execute(); |
1
2
3
4
5
6
|
$stmt = $dbh ->prepare( "SELECT * FROM REGISTRY where name = ?" ); if ( $stmt ->execute( array ( $_GET [ 'name' ]))) { while ( $row = $stmt ->fetch()) { print_r( $row ); } } |
1
2
3
4
5
6
7
8
|
$stmt = $dbh ->prepare( "CALL sp_takes_string_returns_string(?)" ); $value = 'hello' ; $stmt ->bindParam(1, $value , PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); // 调用存储过程 $stmt ->execute(); print "procedure returned $value\n" ; |
1
2
|
$stmt = $dbh ->prepare( "SELECT * FROM REGISTRY where name LIKE ?" ); $stmt ->execute( array ( "%$_GET[name]%" )); |
1
|
PDO::ERRMODE_SILENT |
簡單設置錯誤碼,可使用
1
2
|
PDO::errorCode() PDO::errorInfo() |
1
2
3
4
5
6
7
8
9
10
|
$dsn = 'mysql:dbname=testdb;host=127.0.0.1' ; $user = 'dbuser' ; $password = 'dbpass' ; try { $dbh = new PDO( $dsn , $user , $password ); $dbh ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e ) { echo 'Connection failed: ' . $e ->getMessage(); } |
1
2
3
4
5
6
7
8
9
|
$db = new PDO( 'odbc:SAMPLE' , 'db2inst1' , 'ibmdb2' ); $stmt = $db ->prepare( "select contenttype, imagedata from images where id=?" ); $stmt ->execute( array ( $_GET [ 'id' ])); $stmt ->bindColumn(1, $type , PDO::PARAM_STR, 256); $stmt ->bindColumn(2, $lob , PDO::PARAM_LOB); $stmt ->fetch(PDO::FETCH_BOUND); header( "Content-Type: $type" ); fpassthru ( $lob ); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$db = new PDO( 'odbc:SAMPLE' , 'db2inst1' , 'ibmdb2' ); $stmt = $db ->prepare( "insert into images (id, contenttype, imagedata) values (?, ?, ?)" ); $id = get_new_id(); // 调用某个函数来分配一个新 ID // 假设处理一个文件上传 // 可以在 PHP 文档中找到更多的信息 $fp = fopen ( $_FILES [ 'file' ][ 'tmp_name' ], 'rb' ); $stmt ->bindParam(1, $id ); $stmt ->bindParam(2, $_FILES [ 'file' ][ 'type' ]); $stmt ->bindParam(3, $fp , PDO::PARAM_LOB); $db ->beginTransaction(); $stmt ->execute(); $db ->commit(); |
PDO
PDO::beginTransaction
1
2
3
4
5
6
7
8
9
10
11
12
|
/* 開始一個Transaction,關閉自動提交 */ $dbh ->beginTransaction(); /* 更改資料庫架構及資料 */ $sth = $dbh -> exec ( "DROP TABLE fruit" ); $sth = $dbh -> exec ("UPDATE dessert SET name = 'hamburger' "); /* 識別出錯誤並倒回更改 */ $dbh ->rollBack(); /* 資料庫連接現在返回到自動提交模式 */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/* 開始一個Transaction,關閉自動提交 */ $dbh ->beginTransaction(); /* 在全有或全無的基礎上插入多行記錄(全部插入,全部不插入) */ $sql = 'INSERT INTO fruit (name, colour, calories) VALUES (?, ?, ?)'; $sth = $dbh ->prepare( $sql ); foreach ( $fruits as $fruit ) { $sth ->execute( array ( $fruit ->name, $fruit ->colour, $fruit ->calories, )); } /* 提交更改 */ $dbh ->commit(); /* 現在資料庫連接返回到自動提交模式 */ |
PDO::__construct
1
2
3
4
5
6
7
8
9
10
|
/* Connect to an ODBC database using driver invocation */ $dsn = 'mysql:dbname=testdb;host=127.0.0.1' ; $user = 'dbuser' ; $password = 'dbpass' ; try { $dbh = new PDO( $dsn , $user , $password ); } catch (PDOException $e ) { echo 'Connection failed: ' . $e ->getMessage(); } |
1
2
3
4
5
|
/* 引發一个錯誤 -- BONES 資料表不存在 */ $dbh -> exec ( "INSERT INTO bones(skull) VALUES ('lucy')" ); echo "\nPDO::errorCode(): " ; print $dbh ->errorCode(); // 輸出PDO::errorCode(): 42S02 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/* Provoke an error -- bogus SQL syntax */ $stmt = $dbh ->prepare( 'bogus sql' ); if (! $stmt ) { echo "\nPDO::errorInfo():\n" ; print_r( $dbh ->errorInfo()); } /* PDO::errorInfo(): Array ( [0] => HY000 [1] => 1 [2] => near "bogus": syntax error ) */ |
- PDO::ATTR_AUTOCOMMIT
- PDO::ATTR_CASE
- PDO::ATTR_CLIENT_VERSION
- PDO::ATTR_CONNECTION_STATUS
- PDO::ATTR_DRIVER_NAME
- PDO::ATTR_ERRMODE
- PDO::ATTR_ORACLE_NULLS
- PDO::ATTR_PERSISTENT
- PDO::ATTR_PREFETCH
- PDO::ATTR_SERVER_INFO
- PDO::ATTR_SERVER_VERSION
- PDO::ATTR_TIMEOUT
1
2
3
4
5
6
7
8
9
10
11
|
$conn = new PDO( 'odbc:sample' , 'db2inst1' , 'ibmdb2' ); $attributes = array ( "AUTOCOMMIT" , "ERRMODE" , "CASE" , "CLIENT_VERSION" , "CONNECTION_STATUS" , "ORACLE_NULLS" , "PERSISTENT" , "PREFETCH" , "SERVER_INFO" , "SERVER_VERSION" , "TIMEOUT" ); foreach ( $attributes as $val ) { echo "PDO::ATTR_$val: " ; echo $conn ->getAttribute(constant( "PDO::ATTR_$val" )) . "\n" ; } |
1
|
print_r(PDO::getAvailableDrivers()); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
$sql = 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'; $sth = $dbh ->prepare( $sql , array (PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $sth ->execute( array ( ':calories' => 150, ':colour' => 'red' )); $red = $sth ->fetchAll(); $sth ->execute( array ( ':calories' => 175, ':colour' => 'yellow' )); $yellow = $sth ->fetchAll(); // 執行重複語句 /* Execute a prepared statement by passing an array of values */ $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth ->execute( array (150, 'red' )); $red = $sth ->fetchAll(); $sth ->execute( array (175, 'yellow' )); $yellow = $sth ->fetchAll(); |
PDO::query
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
function getFruit( $conn ) { $sql = 'SELECT name, color, calories FROM fruit ORDER BY name' ; foreach ( $conn ->query( $sql ) as $row ) { print $row [ 'name' ] . "\t" ; print $row [ 'color' ] . "\t" ; print $row [ 'calories' ] . "\n" ; } /* 輸出 apple red 150 banana yellow 250 kiwi brown 75 lemon yellow 25 orange orange 300 pear green 150 watermelon pink 90 /* } |
- column:欄位序號(從1開始索引)或欄位名稱。如果使用欄位名稱,注意名稱應該與由驅動回傳的列名大小寫保持一致。
- param:將綁定到列的 PHP 變數名稱
- type:通過 PDO::PARAM_* 常數指定的參數的資料類型。
- maxlen:預分配提示。
- driverdata:驅動的可選參數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
function readData( $dbh ) { $sql = 'SELECT name, colour, calories FROM fruit' ; try { $stmt = $dbh ->prepare( $sql ); $stmt ->execute(); /* Bind by column number */ $stmt ->bindColumn(1, $name ); $stmt ->bindColumn(2, $colour ); /* Bind by column name */ $stmt ->bindColumn( 'calories' , $cals ); while ( $row = $stmt ->fetch(PDO::FETCH_BOUND)) { $data = $name . "\t" . $colour . "\t" . $cals . "\n" ; print $data ; } } catch (PDOException $e ) { print $e ->getMessage(); } } readData( $dbh ); |
- parameter:參數標識符號。對於使用命名佔位符的預處理語句,應是類似 :name 形式的參數名。對於使用問號佔位符的預處理語句,應是以1開始索引的參數位置。
- variable:綁定到 SQL 語句參數的 PHP 變量名。
- data_type:使用 PDO::PARAM_* 常數明確地指定參數的類型。
- length:資料類型的長度。為表明參數是一個存儲過程的 OUT 參數,必須明確地設置此長度。
- driver_options
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/* Execute a prepared statement by binding PHP variables */ $calories = 150; $colour = 'red' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'); $sth ->bindParam( ':calories' , $calories , PDO::PARAM_INT); $sth ->bindParam( ':colour' , $colour , PDO::PARAM_STR, 12); $sth ->execute(); // 對應的 /* Execute a prepared statement by binding PHP variables */ $calories = 150; $colour = 'red' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth ->bindParam(1, $calories , PDO::PARAM_INT); $sth ->bindParam(2, $colour , PDO::PARAM_STR, 12); $sth ->execute(); |
- parameter:參數標識符。對於使用命名佔位符的預處理語句,應是類似 :name 形式的參數名。對於使用問號佔位符的預處理語句,應是以1開始索引的參數位置。
- value:綁定到參數的值
- data_type:使用 PDO::PARAM_* 常數明確地指定參數的類型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$dbh = new PDO( 'odbc:sample' , 'db2inst1' , 'ibmdb2' ); $sth = $dbh ->prepare( "SELECT name, colour FROM fruit" ); /* Count the number of columns in the (non-existent) result set */ $colcount = $sth ->columnCount(); print ( "Before execute(), result set has $colcount columns (should be 0)\n" ); $sth ->execute(); /* Count the number of columns in the result set */ $colcount = $sth ->columnCount(); print ( "After execute(), result set has $colcount columns (should be 2)\n" ); /* Before execute(), result set has 0 columns (should be 0) After execute(), result set has 2 columns (should be 2) */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
/* Execute a prepared statement by binding PHP variables */ $calories = 150; $colour = 'red' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'); $sth ->bindParam( ':calories' , $calories , PDO::PARAM_INT); $sth ->bindValue( ':colour' , $colour , PDO::PARAM_STR, 12); $sth ->execute(); $sth ->debugDumpParams(); /* SQL: [96] SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour Params: 2 Key: Name: [9] :calories paramno=-1 name=[9] ":calories" is_param=1 param_type=1 Key: Name: [7] :colour paramno=-1 name=[7] ":colour" is_param=1 param_type=2 */ |
1
2
3
4
5
6
|
/* Provoke an error -- the BONES table does not exist */ $err = $dbh ->prepare( 'SELECT skull FROM bones' ); $err ->execute(); echo "\nPDOStatement::errorCode(): " ; print $err ->errorCode(); // PDOStatement::errorCode(): 42S02 |
1 Driver specific error code.
2 Driver specific error message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/* Provoke an error -- the BONES table does not exist */ $sth = $dbh ->prepare( 'SELECT skull FROM bones' ); $sth ->execute(); echo "\nPDOStatement::errorInfo():\n" ; $arr = $sth ->errorInfo(); print_r( $arr ); /* PDOStatement::errorInfo(): Array ( [0] => 42S02 [1] => -204 [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N "DANIELS.BONES" is an undefined name. SQLSTATE=42704 ) */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/* Execute a prepared statement by binding a variable and value */ $calories = 150; $colour = 'gre' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour LIKE :colour'); $sth ->bindParam( ':calories' , $calories , PDO::PARAM_INT); $sth ->bindValue( ':colour' , "%{$colour}%" ); $sth ->execute(); // 以陣列執行 $calories = 150; $colour = 'red' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'); $sth ->execute( array ( ':calories' => $calories , ':colour' => $colour )); //使用?執行 /* Execute a prepared statement by passing an array of insert values */ $calories = 150; $colour = 'red' ; $sth = $dbh ->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth ->execute( array ( $calories , $colour )); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/* Execute a prepared statement using an array of values for an IN clause */ $params = array (1, 21, 63, 171); /* Create a string for the parameter placeholders filled to the number of params */ $place_holders = implode( ',' , array_fill (0, count ( $params ), '?' )); /* This prepares the statement with enough unnamed placeholders for every value in our $params array. The values of the $params array are then bound to the placeholders in the prepared statement when the statement is executed. This is not the same thing as using PDOStatement::bindParam() since this requires a reference to the variable. PDOStatement::execute() only binds by value instead. */ $sth = $dbh ->prepare( "SELECT id, name FROM contacts WHERE id IN ($place_holders)" ); $sth ->execute( $params ); |
- PDO::FETCH_ASSOC
- PDO::FETCH_BOTH
- PDO::FETCH_BOUND
- PDO::FETCH_CLASS
- PDO::FETCH_INTO
- PDO::FETCH_LAZY
- PDO::FETCH_NUM
- PDO::FETCH_OBJ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
$sth = $dbh ->prepare( "SELECT name, colour FROM fruit" ); $sth ->execute(); /* 使用 PDOStatement::fetch 風格 */ print ( "PDO::FETCH_ASSOC: " ); print ( "Return next row as an array indexed by column name\n" ); $result = $sth ->fetch(PDO::FETCH_ASSOC); print_r( $result ); print ( "\n" ); print ( "PDO::FETCH_BOTH: " ); print ( "Return next row as an array indexed by both column name and number\n" ); $result = $sth ->fetch(PDO::FETCH_BOTH); print_r( $result ); print ( "\n" ); print ( "PDO::FETCH_LAZY: " ); print ( "Return next row as an anonymous object with column names as properties\n" ); $result = $sth ->fetch(PDO::FETCH_LAZY); print_r( $result ); print ( "\n" ); print ( "PDO::FETCH_OBJ: " ); print ( "Return next row as an anonymous object with column names as properties\n" ); $result = $sth ->fetch(PDO::FETCH_OBJ); print $result ->NAME; print ( "\n" ); /* PDO::FETCH_ASSOC: Return next row as an array indexed by column name Array ( [name] => apple [colour] => red ) PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number Array ( [name] => banana [0] => banana [colour] => yellow [1] => yellow ) PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties PDORow Object ( [name] => orange [colour] => orange ) PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties kiwi */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
$sth = $dbh ->prepare( "SELECT name, colour FROM fruit" ); $sth ->execute(); /* Fetch all of the remaining rows in the result set */ print ( "Fetch all of the remaining rows in the result set:\n" ); $result = $sth ->fetchAll(); print_r( $result ); /* Array ( [0] => Array ( [name] => pear [0] => pear [colour] => green [1] => green ) [1] => Array ( [name] => watermelon [0] => watermelon [colour] => pink [1] => pink ) ) */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$sth = $dbh ->prepare( "SELECT name, colour FROM fruit" ); $sth ->execute(); print ( "Fetch the first column from the first row in the result set:\n" ); $result = $sth ->fetchColumn(); print ( "name = $result\n" ); print ( "Fetch the second column from the second row in the result set:\n" ); $result = $sth ->fetchColumn(1); print ( "colour = $result\n" ); /* Fetch the first column from the first row in the result set: name = lemon Fetch the second column from the second row in the result set: colour = red */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
$sql = 'CALL multiple_rowsets()' ; $stmt = $conn ->query( $sql ); $i = 1; do { $rowset = $stmt ->fetchAll(PDO::FETCH_NUM); if ( $rowset ) { printResultSet( $rowset , $i ); } $i ++; } while ( $stmt ->nextRowset()); function printResultSet(& $rowset , $i ) { print "Result set $i:\n" ; foreach ( $rowset as $row ) { foreach ( $row as $col ) { print $col . "\t" ; } print "\n" ; } print "\n" ; } /* Result set 1: apple red banana yellow Result set 2: orange orange 150 banana yellow 175 Result set 3: lime green apple red banana yellow */ |
1
2
3
4
5
6
7
8
9
10
11
12
|
/* Delete all rows from the FRUIT table */ $del = $dbh ->prepare( 'DELETE FROM fruit' ); $del ->execute(); /* Return number of rows that were deleted */ print ( "Return number of rows that were deleted:\n" ); $count = $del ->rowCount(); print ( "Deleted $count rows.\n" ); /* Return number of rows that were deleted: Deleted 9 rows. */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100" ; if ( $res = $conn ->query( $sql )) { /* Check the number of rows that match the SELECT statement */ if ( $res ->fetchColumn() > 0) { /* Issue the real SELECT statement and work with the results */ $sql = "SELECT name FROM fruit WHERE calories > 100" ; foreach ( $conn ->query( $sql ) as $row ) { print "Name: " . $row [ 'NAME' ] . "\n" ; } } /* No rows matched -- do something else */ else { print "No rows matched the query." ; } } $res = null; $conn = null; /* apple banana orange pear */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
$sql = 'SELECT name, colour, calories FROM fruit' ; try { $stmt = $dbh ->query( $sql ); $result = $stmt ->setFetchMode(PDO::FETCH_NUM); while ( $row = $stmt ->fetch()) { print $row [0] . "\t" . $row [1] . "\t" . $row [2] . "\n" ; } } catch (PDOException $e ) { print $e ->getMessage(); } /* apple red 150 banana yellow 250 orange orange 300 kiwi brown 75 lemon yellow 25 pear green 150 watermelon pink 90 */ |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
PDOException extends RuntimeException { /* 屬性 */ public array $errorInfo ; protected string $message ; protected string $code ; /* 繼承的方法 */ final public string Exception::getMessage ( void ) final public Exception Exception::getPrevious ( void ) final public int Exception::getCode ( void ) final public string Exception::getFile ( void ) final public int Exception::getLine ( void ) final public array Exception::getTrace ( void ) final public string Exception::getTraceAsString ( void ) public string Exception::__toString ( void ) final private void Exception::__clone ( void ) } |
- errorInfo:相當於PDO::errorInfo() 或 PDOStatement::errorInfo()
- message:文本錯誤訊息。用 Exception::getMessage() 來存取。
- code:SQLSTATE 錯誤碼。用Exception::getCode() 來存取。