ここに質問の内容を詳しく書いてください。 phpでタスク管理のinsertを実行したがpost()の例外処理でcacthしてしまう _save()を実行してtasksテーブルにinsert処理を行いたい ### 発生している問題・エラーメッセージ
エラーメッセージ
public function post(){
try{
$this->_save();
header('Location: http://'.$_SERVER['HTTP_HOST'].'/task.php');
}catch(\Exception $e){
$_SESSION['err'] = $e->getMessage();
echo 'test';
}
exit;
}
$this->_save()を実行したら例外処理を行いinsertに失敗してしまう。
該当のソースコード
php
1<?php 2 3namespace MyApp; 4 5class Task{ 6 private $_db; 7 8 public function __construct(){ 9 $this->_connectDB(); 10 } 11 12 public function post(){ 13 try{ 14 $this->_save(); 15 header('Location: http://'.$_SERVER['HTTP_HOST'].'/task.php'); 16 }catch(\Exception $e){ 17 $_SESSION['err'] = $e->getMessage(); 18 echo 'test'; 19 } 20 exit; 21 } 22 23 public function getError(){ 24 $err = null; 25 if(isset($_SESSION['err'])){ 26 $err = $_SESSION['err']; 27 unset($_SESSION['err']); 28 } 29 return $err; 30 } 31 32 private function _save(){ 33 $sql = "insert into tasks (Title,st_dt,e_dt,state,pri) values (:Title:st_dt,:e_dt,:state,:pri)"; 34 35 $stmt = $this->_db->prepare($sql); 36 $stmt->bindValue(':Title',$_POST['task'],\PDO::PARAM_STR); 37 $stmt->bindValue(':st_dt',$_POST['st_dt'],\PDO::PARAM_STR); 38 $stmt->bindValue(':e_dt',$_POST['e_dt'],\PDO::PARAM_STR); 39 $stmt->bindValue(':state',(int)$_POST['state'],\PDO::PARAM_INT); 40 $stmt->bindValue(':pri',(int)$_POST['pri'],\PDO::PARAM_INT); 41 42 try{ 43 $stmt->execute(); 44 }catch(\PDOException $e){ 45 throw new \Exception('No insert!'); 46 } 47 } 48 49 50 private function _connectDB(){ 51 try{ 52 $this->_db = new \PDO(DSN,DB_USERNAME,DB_PASSWORD); 53 $this->_db->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION); 54 }catch(\PDOException $e){ 55 throw new \Exception('Failed to connect DB'); 56 } 57 } 58} 59 60
dbにinsert できない原因を探してecho 'test';を行なったらpost()の例外処理を行なっていた
回答1件
あなたの回答
tips
プレビュー