Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- try {
- if (!isset($_GET['no'])) {
- throw new RuntimeException('生徒番号が指定されていません', 400);
- }
- $pdo = new PDO(
- 'mysql:dbname=school;host=localhost;charset=utf8',
- 'username',
- 'password',
- array(
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_EMULATE_PREPARES => false,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- )
- );
- $stmt = $pdo->prepare('SELECT * FROM student WHERE no = ? LIMIT 1');
- $stmt->bindValue(1, $_GET['no'], PDO::PARAM_INT);
- $stmt->execute();
- if (!$result = $stmt->fetch()) {
- throw new RuntimeException('番号に一致する生徒は見つかりませんでした', 404);
- }
- header('Content-Type: application/json; charset=utf-8');
- echo json_encode(compact('result'));
- } catch (PDOException $e) {
- header('Content-Type: application/json; charset=utf-8', true, 500);
- $error = 'データベースでエラーが発生しました';
- echo json_encode(compact('error'));
- } catch (RuntimeException $e) {
- header('Content-Type: application/json; charset=utf-8', true, $e->getCode());
- $error = $e->getMessage();
- echo json_encode(compact('error'));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement