Advertisement
Guest User

Untitled

a guest
May 10th, 2014
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2.  
  3. try {
  4.    
  5.     if (!isset($_GET['no'])) {
  6.         throw new RuntimeException('生徒番号が指定されていません', 400);
  7.     }
  8.     $pdo = new PDO(
  9.         'mysql:dbname=school;host=localhost;charset=utf8',
  10.         'username',
  11.         'password',
  12.         array(
  13.             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  14.             PDO::ATTR_EMULATE_PREPARES => false,
  15.             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  16.         )
  17.     );
  18.     $stmt = $pdo->prepare('SELECT * FROM student WHERE no = ? LIMIT 1');
  19.     $stmt->bindValue(1, $_GET['no'], PDO::PARAM_INT);
  20.     $stmt->execute();
  21.     if (!$result = $stmt->fetch()) {
  22.         throw new RuntimeException('番号に一致する生徒は見つかりませんでした', 404);
  23.     }
  24.     header('Content-Type: application/json; charset=utf-8');
  25.     echo json_encode(compact('result'));
  26.    
  27. } catch (PDOException $e) {
  28.    
  29.     header('Content-Type: application/json; charset=utf-8', true, 500);
  30.     $error = 'データベースでエラーが発生しました';
  31.     echo json_encode(compact('error'));
  32.    
  33. } catch (RuntimeException $e) {
  34.    
  35.     header('Content-Type: application/json; charset=utf-8', true, $e->getCode());
  36.     $error = $e->getMessage();
  37.     echo json_encode(compact('error'));
  38.    
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement