calendar 先生版
index.php
<?php
require_once("class/calendar.class.php");
if(empty($_GET["y"]) || empty($_GET["m"])) {
$m = date("n");
$y = date("Y");
} else {
$m = intval($_GET["m"]);
$y = intval($_GET["y"]);
}
$cal = new Calendar($y, $m);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>カレンダー</title>
<link rel="stylesheet" href="css/style.css">
<script src="../jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="container">
<div id="calendar">
<?php $cal->makeCalendar($y, $m); ?>
</div>
</div>
<script src="js/calendar.js"></script>
</body>
</html>
calendar.class.php
<?php
class Calendar {
private $pdo;
private $scheArr;
public function __construct($y, $m) {
// ---- DB接続情報 ----
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "calendar";
// --------------------
$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8";
$this->pdo = new PDO($dsn, $dbuser, $dbpass);
$this->scheArr = $this->getSchedule($y, $m);
}
private function getSchedule($y, $m) {
$sql = "SELECT d,schedule FROM schedules WHERE y=:y AND m=:m";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(":y", $y, PDO::PARAM_INT);
$stmt->bindValue(":m", $m, PDO::PARAM_INT);
$stmt->execute();
$rows = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[$row["d"]] = $row["schedule"];
}
return $rows;
}
private function makeHeader($y, $m) {
$weeks = ["月","火","水","木","金","土","日"];
echo "<div id=\"ym\">{$y}年{$m}月</div>";
foreach($weeks as $val) {
echo "<div class=\"head\">{$val}</div>";
}
}
public function makeCalendar($y, $m) {
$this->makeHeader($y, $m);
$last_day = date("t", mktime(0, 0, 0, $m, 1, $y));
$w_of_1 = date("w", mktime(0, 0, 0, $m, 1, $y));
if($w_of_1 == 0) $w_of_1 = 7;
// 空白マス出力
for($i=$w_of_1; $i>1; $i--) {
echo "<div></div>\n";
}
// 日付マス出力
for($i=1; $i<=$last_day; $i++) {
if(empty($this->scheArr[$i])) {
echo "<div>{$i}</div>\n";
} else {
echo "<div>{$i}<p>{$this->scheArr[$i]}</p></div>\n";
}
}
}
}
?>
style.css
body {
background: #fcc;
}
#container {
width: 80%;
background: #fff;
margin: auto;
}
#calendar {
display: flex;
flex-wrap: wrap;
}
#calendar div {
width: 14.2857%;
box-sizing: border-box;
border: solid 1px #000;
text-align: center;
padding-bottom: 2rem;
padding-top: 0.5rem;
position: relative;
}
#calendar div.head {
padding: 0.2rem;
}
/* modified 3/23 */
#calendar div#ym {
border: solid 1px #000;
text-align: center;
padding: 0.2rem;
width: 100%;
}
#calendar div p {
position: absolute;
top: 1.8rem;
left: 0.15rem;
margin: 0;
padding: 0.1rem;
font-size: 0.7rem;
height: 0.7rem;
overflow: hidden;
color: #fff;
background: #66f;
border-radius: 0.5rem;
}
calendar.js
$(function() {
console.log('OK');
});