以下がindex.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="XXX">
<meta name="description" content="XXX">
<title>XXX</title>
<link rel="stylesheet" href="/main.css">
</head>
<body>
<?php
try {
//DB名、ユーザー名、パスワード
$dsn = 'mysql:dbname=XXX;host=XXX';
$user = 'XXX';
$password = 'XXX';
$PDO = new PDO($dsn, $user, $password); //MySQLのデータベースに接続
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //PDOのエラーレポートを表示
$sql = "SELECT * FROM contents"; //SELECT文を変数に格納
$stmt = $PDO->query($sql); // SQLステートメントを実行し、結果を変数に格納
// foreach文で配列の中身を一行ずつ出力
foreach ($stmt as $row) {
echo "<a href='https://thejoinery.jp/item.php?id=";
echo $row['id'];
echo "'>";
echo $row['name_en']."<br/>";
}
} catch (PDOException $e) {
exit('データベースに接続できませんでした。' . $e->getMessage());
}
?>
<?php echo $rows; ?>
</body>
</html>
以下が個別ページ
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="XXX">
<meta name="description" content="XXX">
<title>XXX</title>
<link rel="stylesheet" href="/main.css">
</head>
<body>
<?php
try {
//URLのidの値を取得
$id = $_GET['id'];
//DB名、ユーザー名、パスワード
$dsn = 'mysql:dbname=XXX;host=XXX';
$user = 'XXX';
$password = 'XXX';
$PDO = new PDO($dsn, $user, $password); //MySQLのデータベースに接続
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $PDO->query("SELECT id FROM contents WHERE id = '$id'");
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$rows .= $row['id']."</br>";
}
} catch (PDOException $e) {
exit('データベースに接続できませんでした。' . $e->getMessage());
}
?>
<?php echo $rows; ?>
</body>
</html>