PHP5增加了PDO(PHP Data Objects)的extension
PDO以物件導向的概念,需要更換資料庫的時候,不用更動到原來的程式碼,較為方便。
連線方式:
[php]
<?php
//$db_type = ‘mysql’;
$db_host = ‘localhost’;
$db_name = ‘dbname’;
$db_user = ‘username’;
$db_passwd = ‘password’;
$dsn = ‘mysql: host=’ . $db_host . ‘; dbname=’ . $db_name;
/**Connect to a database**/
try {
$dbh = new PDO( $dsn, $db_user, $db_passwd );
/*Database use UTF-8*/
$dbh -> query(‘SET NAMES UTF8’);
} catch( PDOException $e ) {
die( $e->getMessage() );
}
?>
[/php]
[php]
<?php
/*讀取test_tb資料表所有資料*/
$rs = $dbh -> query(‘SELECT * FROM test_tb ;’);
$rows = $rs -> fetch();
/*資料總筆數*/
$rs -> rowCount();
?>
[/php]
防止SQL injection
如果用 mysql function, 採用 mysql_real_escape_string 過濾字串,若使用的是PDO,則用bind value作法
[php]
<?php
$sql = "INSERT INTO test_table
VALUES(”, ?, ?, ‘test’)";
$sth = $dbh -> prepare($sql);
/*以陣列輸入*/
$sth -> execute( array($_POST[‘id’], $_POST[‘name’]));
?>
[/php]