· 8 years ago · May 10, 2018, 04:18 PM
1//Classe abstraite Engine, peut être améliorée via singleton
2<?php
3class Engine
4{
5 protected $sqlCon;
6 protected $db;
7
8
9 public function __construct($host, $db, $user, $pass)
10 {
11 if(empty($host)) $host = 'localhost';
12 if(empty($db)) $db = 'trends';
13 if(empty($user)) $user = 'root';
14
15 try
16 {
17 $this->sqlCon = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
18 //$this->sqlCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
19 $this->db = $db;
20 }
21 catch(PDOException $e)
22 {
23 echo '<p class="error">';
24 echo 'PDO Error : '.$e->getMessage().'<br />';
25 echo 'N° : '.$e->getCode();
26 echo '</p>';
27 }
28 }
29
30 protected function sqlQuery($query, $params=array(''))
31 {
32 try
33 {
34 $prep_req = $this->sqlCon->prepare($query);
35 $prep_req->execute($params);
36 $reply = $prep_req->fetchAll(PDO::FETCH_OBJ);
37 $prep_req->closeCursor();
38 return $reply;
39 }
40 catch(PDOException $e)
41 {
42 echo '<p class="error">';
43 echo 'Error : '.$e->getMessage().'<br />';
44 echo 'N° : '.$e->getCode().'<br />';
45 echo 'Request: '.$query.'<br />';
46 echo 'Parameters: <br />';
47 var_dump($params);
48 echo '</p>';
49 }
50 }
51}
52?>
53
54//Classe héritant d'Engine
55<?php
56class GoogleTrends extends Engine
57{
58 protected $date;
59 protected $now;
60 protected $result;
61 protected $update;
62
63 public function __construct($host, $db, $user, $pass)
64 {
65 try
66 {
67 parent::__construct($host, $db, $user, $pass);
68 $this->date = new DateTime();
69 $this->now = clone $this->date;
70 $this->update = FALSE;
71
72 $query = "SHOW TABLES LIKE ?";
73 $params = array('Google_Trends');
74 $reply = $this->sqlQuery($query, $params);
75 if (empty($reply)) $this->install();
76 }
77 catch(PDOException $e)
78 {
79 echo '<p class="error">';
80 echo 'PDO Error : '.$e->getMessage().'<br />';
81 echo 'N° : '.$e->getCode();
82 echo '</p>';
83 }
84 }
85
86 //protected install(): void; - Creates Google HotTrends table
87 protected function install()
88 {
89 $query = "CREATE TABLE IF NOT EXISTS `Google_Trends` ("
90 ."`id` int(11) NOT NULL AUTO_INCREMENT,"
91 ."`keywords` text NOT NULL,"
92 ."`rank` int(11) NOT NULL,"
93 ."`date` date NOT NULL,"
94 ."PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
95
96 $this->sqlQuery($query);
97 }
98...
99}