Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2017
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.33 KB | None | 0 0
  1. <?php
  2.  
  3. $db = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
  4.  
  5. $res = $db->prepare("INSERT INTO students (first_name, last_name, student_id, phone) VALUES (:first_name, :last_name, :student_id, :phone)");
  6.  
  7. $n = intval(trim(fgets(STDIN)));
  8.  
  9. for ($i = 0; $i < $n; $i++) {
  10.     try {
  11.         $input = explode(" ", trim(fgets(STDIN)));
  12.  
  13.         $first_name = $input[0];
  14.         $last_name = $input[1];
  15.         $student_id = $input[2];
  16.         $phone = null;
  17.  
  18.         if ($first_name == '') {
  19.             throw new PDOException("First Name cannot be empty!");
  20.         }
  21.         elseif (preg_match('~[0-9]~', $first_name)) {
  22.             throw new PDOException("First Name must contain only letters!");
  23.         }
  24.         elseif ($last_name == '') {
  25.             throw new PDOException("Last Name cannot be empty!");
  26.         }
  27.         elseif (preg_match('~[0-9]~', $last_name)) {
  28.             throw new PDOException("Last Name must contain only letters!");
  29.         }
  30.         elseif (!is_numeric($student_id)) {
  31.             throw new PDOException("Invalid Student ID");
  32.         }
  33.  
  34.         $res->execute([':first_name' => $first_name, 'last_name' => $last_name, 'student_id' => $student_id, 'phone' => $phone]);
  35.  
  36.         $res = null;
  37.         $db = null;
  38.     }
  39.     catch (PDOException $e) {
  40.         echo $e->getMessage();
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement