2019鐵人賽
PHP 取 MySQL 資料,有幾點需要搞定。
<?php
// 建立連線
$db_link = mysqli_connect('127.0.0.1', 'root', '', '', '3306');
// 連線失敗
if (!$db_link) {
die("Connection failed: " . mysqli_connect_error());
}
// 選擇資料庫
$select_db = mysqli_select_db($db_link, "school");
// 選擇資料庫失敗
if (!$select_db) {
die("Select database failed: " . mysqli_error($db_link));
}
// Query Database
$result = mysqli_query($db_link, "SELECT * FROM student");
// 將 query 結果取出
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "id: {$row['id']}, name: {$row['name']}, birthday: {$row['birthday']}, address: {$row['address']}\n";
}
} else {
echo "0 row";
}
// 斷開連線
mysqli_close($db_link);
?>
結果
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/function.mysqli-connect.php
reference from http://php.net/manual/en/mysqli.select-db.php
reference from http://php.net/manual/en/mysqli.error.php
reference from http://php.net/manual/en/mysqli.query.php
reference from http://php.net/manual/en/mysqli-result.num-rows.php
reference from http://php.net/manual/en/mysqli-result.fetch-assoc.php