資料庫架構:
程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>PDO</title> </head> <body> <?php $db = new PDO('mysql:host=localhost;dbname=test', '帳號', '密碼', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';")); try{ $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->beginTransaction(); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '高雄國小')"); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '台北國小')"); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '台中國小')"); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '花蓮國小')"); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '宜蘭國小')"); $db->exec("INSERT INTO `school` (`number`, `name`) VALUES(NULL, '屏東國小')"); $db->commit(); }catch(PDOException $ex){ echo $ex; $db->rollBack(); } foreach ($db->query('SELECT * from school') as $data) { echo "Number $data[0] ,Name=$data[1]<br>"; } $db = null; ?> </body> </html>
結果:
參考資料:
http://tw1.php.net/manual/en/intro.pdo.php
http://www.php.net/manual/en/pdo.construct.php
http://tw1.php.net/manual/en/pdo.constants.php
http://tw2.php.net/manual/en/language.types.array.php
http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2009/0720/3085.html
http://tw1.php.net/manual/en/pdo.transactions.php