前提・実現したいこと
ドットインストールのphpのレッスン「PHP5.6で投票システムを作ろう」をxamppを使ってやっている途中です。
投票ボタンを押してデータベースに投票内容を保存しようとしたところで以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
Uncaught Error: Call to a member function prepare() on null
該当のソースコード
public function _save(){ $stmt = $this->_db->prepare('INSERT INTO answers (answer, created) VALUE (:answer, now())'); $stmt->bindValue(':answer', (int)$_POST['answer'], PDO::PARAM_INT); $stmt->execute(); exit; }
試したこと
dbへの接続はpdoを使ったので$this->_dbのところを$pdoに変えて試したのですが同じエラーメッセージが出ました。
prepare()の値の受け渡しかたに問題があると思うのですが、レッスン通りに文字コードを書いているのでどこが間違えているのかわかりません。
お手数ですがご教授お願いします
<?php // index.php require_once("config.php"); require_once("Poll.php"); try{ $poll = new Poll(); }catch(Exception $e){ echo $e->getMessage(); exit; } if($_SERVER['REQUEST_METHOD'] === 'POST'){ $poll->post(); } $err = $poll->getError(); ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Poll</title> <link rel="stylesheet" href="styles.css"> </head> <body> <?php if(isset($err)) : ?> <div class="error"><?= h($err);?></div> <?php endif ;?> <h1>Which do you like best?</h1> <form action="" method="POST"> <div class="row"> <div class="box " id="box_0" data-id="0"></div> <div class="box " id="box_1" data-id="1"></div> <div class="box " id="box_2" data-id="2"></div> <input type="hidden" id="answer" name="answer" value=""> <!--<input type="hidden" name="token" value="<?= h($_SESSION['token']); ?>">--> </div> <div id="btn">Vote and See Results </div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(function(){ 'use script'; $('.box').on('click',function(){ $('.box').removeClass('selected'); $(this).addClass('selected'); $('#answer').val($(this).data('id')); }); $('#btn').on('click',function(){ if($('#answer').val() === ''){ alert('Choose One!'); } else{ $('form').submit(); } }); $('.error').fadeout(3000); }); </script> </body> </html>
<?php // Poll.php class Poll { private $_db; public function __construct(){ $this->_connectDB(); //$this->_createToken(); } private function _createToken(){ if(!isset($_SESSION['token'])){ $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(16)); } } public function _validateToken(){ if( !isset($_SESSION['token']) || !isset($_POST['token']) || $_SESSION['token'] !== $_POST['token'] ){ throw new Exception('invalid Token!'); } } public function post(){ try{ //$this->_validateToken(); $this->_validateAnswer(); $this->_save(); //redirect to result.php header('Location: http://'. $_SERVER['HTTP_HOST']. '/result.php'); } catch(Exception $e){ //set error $_SESSION['err'] = $e->getMessage(); //redirect to index.php header('Location: http://'. $_SERVER['HTTP_HOST'] ); } exit; } public function getError(){ $err = null; if(isset($_SESSION['err'])){ $err = $_SESSION['err']; unset($_SESSION['err']); } return $err; } private function _validateAnswer(){ if( !isset($_POST['answer']) || !in_array($_POST['anawer'], [0, 1, 2]) ){ throw new Exception('invailed answer!'); } } public function _save(){ $stmt = $this->_db->prepare('INSERT INTO answers (answer, created) VALUE (:answer, now())'); $stmt->bindValue(':answer', (int)$_POST['answer'], PDO::PARAM_INT); $stmt->execute(); exit; } public function _connectDB(){ try { $dsn = "mysql:dbname=poll_php;host=localhost;charset=utf8mb4"; $username = "root"; $password = ""; $options = []; $pdo = new PDO($dsn, $username, $password, $options); } catch (Exception $e) { echo 'エラーが発生しました。:' . $e->getMessage(); } } }
<?php // functions.php function h($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
<?php // config.php session_start(); require_once("functions.php");

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/08/18 08:30