2019鐵人賽
也可以使用 PDO 方法來操作 MySQL
<?php
// 錯誤處理
try {
// 連線資料庫
$db_link = new PDO('mysql:host=127.0.0.1:3306;dbname=school', 'root', '');
} catch (PDOException $e) {
die("連接資料庫失敗,訊息:" . $e->getMessage());
}
// Query Database
$result = $db_link->query("SELECT * FROM student");
// 將 query 結果取出
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo "id: {$row['id']}, name: {$row['name']}, birthday: {$row['birthday']}, address: {$row['address']}\n";
}
} else {
echo "0 row";
}
// 解構 PDO
$db_link = null;
?>
結果
id: 1, name: Hank, birthday: 1911-01-01, address: Taiwan
id: 2, name: Jim, birthday: 1921-12-05, address: China
reference from http://php.net/manual/en/book.pdo.php
reference from http://php.net/manual/en/class.pdoexception.php
reference from http://php.net/manual/en/pdo.query.php