teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

まとめサンプルコード

2018/04/05 01:07

投稿

m.ts10806
m.ts10806

スコア80888

answer CHANGED
@@ -12,4 +12,49 @@
12
12
  function __construct()
13
13
 
14
14
  //以下略
15
+ ```
16
+
17
+ # まとめサンプルコード
18
+
19
+ ```php
20
+ class Database
21
+ {
22
+ protected $dbh;
23
+ function getDBH()
24
+ {
25
+ try{
26
+ $dsn = 'mysql:host=localhost; dbname=test1;charset=utf8;';
27
+ $user = 'root';
28
+ $password = 'root';
29
+ $this->dbh = new PDO($dsn, $user,$password);
30
+ $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
31
+ $this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
32
+ $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
33
+ }catch(PDOException $e){
34
+ die($e->getMessage());
35
+ }
36
+ }
37
+ }
38
+
39
+ class DataSelect extends Database
40
+ {
41
+ function __construct()
42
+ {
43
+ $this->getDBH();
44
+ }
45
+ function test()
46
+ {
47
+ try{
48
+ $sql="SELECT * FROM tb";
49
+ $stmt = $this->dbh->prepare($sql);
50
+ $stmt->execute([]);
51
+ $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
52
+ print_r($rows);
53
+ }catch(PDOException $e){
54
+ die($e->getMessage());
55
+ }
56
+ }
57
+ }
58
+ $myExec=new DataSelect;
59
+ $myExec->test();
15
60
  ```