###前提・実現したいこと
MVCとクラスについて勉強中です。
とりあえずModel部分を作ろうとしています。
DB接続とデータ加工までをModelでやって、controllerで呼び出せるようにしたいです。
###発生している問題・エラーメッセージ
Fatal error: Uncaught Error: Using $this when not in object context in Model.php:53 Stack trace: #0 controller.php(11): DBconnect::getList() #1 {main} thrown in Model.php on line 53
###該当のソースコード
php
1 2if(isset($_POST['item_id'])){ 3 $input_item_id = $_POST['item_id']; 4} else{ 5 $input_item_id = null; 6 //★エラーを表示させる? 7} 8if(isset($_POST['type'])){ 9 $input_item_type = $_POST['type']; 10} else{ 11 $input_item_type = null; 12 //★エラーを表示させる? 13} 14if(isset($_POST['maker'])){ 15 $input_item_maker_id = $_POST['maker']; 16} else{ 17 $input_item_maker_id = null; 18 //★エラーを表示させる? 19} 20 21class DBconnect 22{ 23 public $db; 24 private $host = 'xxx'; 25 private $dbname = 'xxx'; 26 private $dbuser = 'xxx'; 27 private $password = 'xxx'; 28 29 public function __construct() 30 { 31 $dsn = sprintf( 32 'mysql:host=%s;dbname=%s;charset=utf8', 33 $this->host, $this->dbname 34 ); 35 try{ 36 $this->db = new PDO($dsn, $this->dbuser, $this->password); 37 } catch (PDOException $e) { 38 header('Content-Type: text/plain; charset=UTF-8', true, 500); 39 exit($e->getMessage()); 40 } 41 } 42 43 // 商品リスト取得 44 public function getList() 45 { 46 $sql = 'SELECT * FROM data where data.id = ?'; 47 $stmt = $this->db->prepare($sql); //ここでエラーが出ます 48 $stmt->execute(['sample']); 49 $rows = $stmt->fetchAll(); 50 return $rows; 51 } 52}
php
1include(dirname(__FILE__) . "/model.php"); 2new DBconnect; 3DBconnect::getList();
###試したこと
$stmt = $this->db->query($sql)
⇒ $stmt = self::$db->query($sql)
と書き換えてみましたが、Access to undeclared static propertyと怒られました。
###補足情報(言語/FW/ツール等のバージョンなど)
PHP7.1.8

回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/07 03:04