Advertisement
Guest User

MySQLandPHPBasicsExercise_7.CallCenterApplication

a guest
Oct 21st, 2017
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.20 KB | None | 0 0
  1. // file CallCenter.php
  2. <?php
  3. class CallCenter{
  4.     private $dbi = false;
  5.  
  6.     public function connectDB()
  7.     {
  8.         $db = new Database();
  9.         $this->dbi = $db->connect();
  10.     }
  11.  
  12.     public function __construct()
  13.     {
  14.         $this->connectDB();
  15.     }
  16.  
  17.     public function main()
  18.     {
  19.         do{
  20.             $input_str = trim(fgets(STDIN));
  21.             $res = $this->getCountryInfo($input_str);
  22.             if($res != false){
  23.                 $flag = false;
  24.                 foreach ($res as $i=>$iv){
  25.                     echo "Country: " . $iv['country_name'] . "\r\n";
  26.                     echo "Capital: " . $iv['capital'] . "\r\n";
  27.                     $flag = true;
  28.                     break;
  29.                 }
  30.                 if($flag == false){
  31.                     echo "Country not found.";
  32.                 }
  33.             }else{
  34.                 echo "Could not read from DB.";
  35.             }
  36.         }
  37.         while($input_str != 'Bye');
  38.     }
  39.  
  40.     private function getCountryInfo($str)
  41.     {
  42.         $result = $this->dbi->query("
  43.            SELECT `country_name`, `capital`
  44.            FROM `countries`
  45.            WHERE `country_name` = \"$str\"
  46.            OR `country_code` = \"$str\"
  47.                    OR `iso_code` = \"$str\"
  48.                    LIMIT 0,1 ");
  49.  
  50.         if (is_object($result)){
  51.             return($result);
  52.         }
  53.         else{
  54.             return false;
  55.         }
  56.  
  57.     }
  58. }
  59.  
  60. // file Database.php
  61. <?php
  62. class Database extends PDO
  63. {
  64.     private $db_host = "localhost";
  65.     private $db_name = "geography";
  66.     private $db_user = "root";
  67.     private $db_password = "";
  68.     private $db = false;
  69.  
  70.     public function __construct()
  71.     {
  72.         parent::__construct("mysql:dbname=" . $this->db_name . ";host=" . $this->db_host, $this->db_user, $this->db_password);
  73.     }
  74.  
  75.     public function setErrorExeption()
  76.     {
  77.         $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  78.     }
  79.  
  80.     public function connect()
  81.     {
  82.         $this->setErrorExeption();
  83.         return $this;
  84.     }
  85. }
  86.  
  87. // file callcenter_app.php
  88. <?php
  89. include 'Database.php';
  90. include 'CallCenter.php';
  91.  
  92. $app = new CallCenter();
  93. $app->main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement