데이터베이스 연동

PHP
<?php
$host = 'localhost'; // DB 호스트
$dbname = 'test'; // 데이터베이스 이름
$username = 'test'; // DB 사용자명
$password = 'example'; // DB 비밀번호

// MySQL 연결
$conn = new mysqli($host, $username, $password, $dbname);

// 연결 오류 확인
if ($conn->connect_error) {
    die("연결 실패: " . $conn->connect_error);
}

// 데이터 조회 SQL
$sql = "SELECT *, (total/3) as average FROM student";
$result = $conn->query("set names utf8");
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>학생 성적표</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>

<h2>학생 성적표</h2>

<table>
    <tr>
        <th>ID</th>
        <th>이름</th>
        <th>국어</th>
        <th>영어</th>
        <th>수학</th>
        <th>총점</th>
        <th>평균</th>
    </tr>

    <?php
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td>{$row['id']}</td>
                    <td>{$row['name']}</td>
                    <td>{$row['korean']}</td>
                    <td>{$row['math']}</td>
                    <td>{$row['english']}</td>
                    <td>{$row['total']}</td>
                    <td>{$row['average']}</td>
                  </tr>";
        }
    } else {
        echo "<tr><td colspan='7'>데이터가 없습니다.</td></tr>";
    }
    ?>

</table>

</body>
</html>

<?php
$conn->close();
?>

For You

2 Comments

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다