php 連線 MySQL 資料庫
環境
遠端主機 cloudways
MariaDB 10.4
php 7.4
建立 MySQL 資料表
-- ----------------------------
-- Table structure for test01
-- ----------------------------
DROP TABLE IF EXISTS `test01`;
CREATE TABLE `test01` (
`id` int(11) NOT NULL,
`int_test` int(11) NOT NULL,
`char_test` char(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`varchar_test` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`text_test` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of test01
-- ----------------------------
INSERT INTO `test01` VALUES (1, 10, 'a', 'Harry Potter', 'The novels chronicle the lives of a young wizard, Harry Potter, whom are students at Hogwarts School of Witchcraft and Wizardry.');
INSERT INTO `test01` VALUES (2, 20, 'b', '哈利波特', '是一部兒童奇幻文學系列小說,描寫主角哈利波特在霍格華茲魔法學校7年學習生活中的冒險故事。');
INSERT INTO `test01` VALUES (3, 30, 'c', 'ハリー・ポッター', '1990年代のイギリスを舞台に、魔法使いの少年ハリー・ポッターの学校生活。');
SET FOREIGN_KEY_CHECKS = 1;
cloudways 網頁顯示
php 程式碼 – sqltest0201.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PHP與MySQL建立網頁資料庫</title>
</head>
<body>
<?php
// 建立MySQL的資料庫連接
$host = "localhost";
$dbuser = "user";
$dbpassword = "password";
$dbname = "database";
$link = mysqli_connect($host,$dbuser,$dbpassword,$dbname);
if ( !$link )
{
echo "不正確連接資料庫 " . mysqli_connect_error();
echo "<br>";
exit();
}
echo "MySQL資料庫連接成功";
echo "<br>";
mysqli_query($link, "SET NAMES utf8");
mysqli_query($link, "SET CHARACTER_SET_database= utf8");
mysqli_query($link, "SET CHARACTER_SET_CLIENT= utf8");
mysqli_query($link, "SET CHARACTER_SET_RESULTS= utf8");
$sql = "select * from test01";
echo $sql;
echo "<br>";
$result = mysqli_query($link, $sql);
if (!$result)
{
echo "{$sql} 語法執行失敗,錯誤訊息 " . mysqli_error($link);
echo "<br>";
mysqli_close($link); // 關閉資料庫連接
exit();
}
echo "sql 語法執行成功";
echo "<br>";
echo "<br>";
$rowNum = mysqli_num_rows($result);
if ($rowNum <= 0)
{
echo "沒有資料";
echo "<br>";
mysqli_close($link); // 關閉資料庫連接
exit();
}
while ($row = mysqli_fetch_assoc($result))
{
// 每跑一次迴圈就抓一筆值,放進 data 陣列中
$datas[] = $row;
}
print_r($datas);
echo "<br>";
echo "<br>";
for ( $i=0 ; $i<$rowNum ; $i++ )
{
print_r($datas[$i]);
echo "<br>";
}
echo "<br>";
echo $datas[2]["id"];
echo "<br>";
echo $datas[2]["int_test"];
echo "<br>";
echo $datas[2]["char_test"];
echo "<br>";
echo $datas[2]["varchar_test"];
echo "<br>";
echo $datas[2]["text_test"];
echo "<br>";
mysqli_free_result($result);
mysqli_close($link); // 關閉資料庫連接
?>
</body>
</html>
執行結果