2014-02-26 3 views
0

내 웹 사이트에 대한 로그인 시스템을 구축 중입니다. 데이터베이스에 저장된 사용자 세부 정보를 업데이트 할 때까지 모든 것이 제대로 작동하는 것처럼 보였습니다. 더미 세부 정보를 업데이트하려고 할 때마다 예외가 발생하고 이유를 파악할 수 없습니다.PHP 예외 오류가 발생했습니다

신속하게 스캔하여 오류가 있는지 찾아 볼 수 있습니까? 구문 오류가 없습니다.

update.php

$user = new User(); 
      if(!$user->isLoggedIn()){ 
       Redirect::to('index.php'); 
      } 

      // Check whether token is submited and user exists 
      if(Input::exists()){ 
       if(Token::check(Input::get('token'))){ 

        $validate = new Validate(); 
        $validation = $validate->check($_POST, array(
         'Name' => array(
          'required' => true, 
          'min' => 4, 
          'max' => 30 
         ), 
         'email' => array(
          'required' =>true 
         ) 
        )); 

        if($validation->passed()){ 
         // Update 

         try{ 
          $user->update(array(
           'Name' => Input::get('Name'), 
           'email' => Input::get('email') 
          )); 

       Session::flash('home', 'Your details have been updated'); 
       Redirect::to('index.php'); 

         }catch(Exception $e) { 
          die($e->getMessage()); 
         } 

        } else { 
         foreach($validation->errors() as $error){ 
          echo ('<p>' . $error . '</p>'); 
         } 
        } 
       } 
      } 

User.php 클래스

class User{ 
    private $_db, 
      $_data, 
      $_sessionName, 
      $_cookieName, 
      $_isLoggedIn; 

    public function __construct($user = null){ 
     $this->_db = DB::getInstance(); 

     $this->_sessionName = Config::get('session/session_name'); 
     $this->_cookieName = Config::get('remember/cookie_name'); 


     if(!$user){ 
      if(Session::exists($this->_sessionName)){ 
       $user = Session::get($this->_sessionName); 

       if($this->find($user)){ 
        $this->_isLoggedIn = true; 
       } else { 
        // Process Log out 
       } 
      } 
     } else { 
      $this->find($user); 
     } 
    } 

    public function update($fields = array(), $id = null){ 

     if(!$id && $this->isLoggedIn()){ 
      $id = $this->data()->id; 
     } 

     if(!$this->_db->update('user', $id, $fields)){ 
    throw new Exception('Sorry, there was problem updating. Please try again later.'); 
     } 

    } 

    public function create($fields = array()){ 
     if(!$this->_db->insert('user', $fields)){ 
      throw new Exception('There was a problem creating new account.'); 
     } 
    } 

    public function find($user = null){ 
     if($user){ 
      $field = (is_numeric($user)) ? 'id' : 'Username'; 
      $data = $this->_db->get('user', array($field, '=', $user)); 

      if($data->count()){ 
       $this->_data = $data->first(); 
       return true; 
      } 
     } 

     return false; 
    } 

    public function login($Username = null, $password = null, $remember = false){ 



     if(!$Username && !$password && $this->exists()){ 
      // Log User in 

      Session::put($this->_sessionName, $this->data()->id); 
     } else { 

      $user = $this->find($Username); 
      if($user){ 
       if($this->data()->Password === Hash::make($password, $this->data()->salt)){ 
        Session::put($this->_sessionName, $this->data()->id); 

        if($remember){ 
         $hash = Hash::unique(); 
         $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id)); 

         if(!$hashCheck->count()){ 
          $this->_db->insert('users_session', array(
           'user_id' => $this->data()->id, 
           'hash' => $hash 
          )); 
         } else { 
          $hash = $hashCheck->first()->hash; 
         } 

         Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry')); 
        } 

        return true; 
       } 
      } 
     } 

     return false; 
    } 

    public function exists(){ 
     return (!empty($this->_data)) ? true : false; 
    } 

    public function logout(){ 

     $this->_db->delete('users_session', array('user_id', '=', $this->data()->id)); 

     Session::delete($this->_sessionName); 
     Cookie::delete($this->_cookieName); 
    } 

    public function data(){ 
     return $this->_data; 
    } 

    public function isLoggedIn(){ 
     return $this->_isLoggedIn; 
    } 
} 

(경우 ($이 -!> _ DB-> 갱신 ('사용자', $ 아이디, $ 필드)) { 던져 새로운 예외 ('.. 죄송합니다, 문제 업데이트 나중에 다시 시도하십시오 있었다'); })

이 내가 얻을의 예외입니다 .. 감사합니다 만

이 업데이트는() 도움이된다면이 내 DB 클래스입니다 내가

에서 오류가 발생하는 방법입니다 : 그것은 아니라는 것을 당신은 발견 할 것이다 SQL을 반환하려고하면

class DB{ 
     private static $_instance = null; 
     private $_pdo, 
       $_query, 
       $_error = false, 
       $_results, 
       $_count = 0; 


     private function __construct(){ 

      try { 
       $this->_pdo = new PDO('mysql:host=' . 
         Config::get('mysql/host') . ';dbname=' . 
         Config::get('mysql/db'), 
         Config::get('mysql/username'), 
         Config::get('mysql/password')); 

      } catch(PDOException $e){ 
       die($e -> getMessage()); 
      } 
     } 

     public static function getInstance(){ 
      if(!isset(self::$_instance)) { 
       self::$_instance = new DB(); 
      } 
      return self::$_instance; 
     } 

     public function query($sql, $params = array()){ 

      $this->_error = false; 

      // Check if query has been prepared properly 

      if($this->_query = $this->_pdo->prepare($sql)){ 

       $x = 1; 
       if(count($params)){ 
        foreach($params as $param){ 
         $this->_query->bindValue($x, $param); 
         $x++; 
        } 
       } 

      // If the query has been prepared successfuly, store the result 
       if($this->_query->execute()){ 
        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 
        $this->_count = $this->_query->rowCount(); 
       } else { 
        $this->_error = true; 
       } 
      } 

      return $this; 
     } 

     public function action($action, $table, $where = array()){ 
      if(count($where) === 3){ 
       $operators = array('=', '>', '<', '>=', '<='); 

       $field  = $where[0]; 
       $operator = $where[1]; 
       $value  = $where[2]; 

       if(in_array($operator, $operators)){ 
        $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; 

        if(!$this->query($sql, array($value))->error()){ 
         return $this; 
        } 
       } 
      } 

      return false; 
     } 

     // QUERYING DATA FROM DATABASE 
     public function get($table, $where){ 
      return $this->action('SELECT *', $table, $where); 
     } 

     // DELETING DATA FROM DATABASE 
     public function delete($table, $where){ 
      return $this->action('DELETE', $table, $where); 
     } 

     // INSERTING DATA INTO DATABASE 
     public function insert($table, $fields = array()){ 
       $keys = array_keys($fields); 
       $values = ''; 
       $x = 1; 

       foreach($fields as $field){ 
        $values .= "?"; 

        if($x < count($fields)){ 
         $values .= ', '; 
        } 
        $x++; 
       } 

       $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES({$values})"; 

       if(!$this->query($sql, $fields)->error()){ 
        return true; 
       } 

      return false; 
     } 

     public function results(){ 
      return $this->_results; 
     } 

     public function update($table, $userID, $fields){ 
      $set = ''; 
      $x = 1; 

      foreach($fields as $name => $value){ 
       $set .= "{$name} = ?"; 

       if($x < count($fields)){ 
        $set .= ', '; 
       } 
       $x++; 
      } 


      $sql = "UPDATE {$table} SET {$set} WHERE userID = {ID}"; 

      if(!$this->query($sql, $fields)->error()){ 
       return true; 
      } 

      return false; 
     } 

     public function first(){ 
      return $this->results()[0]; 
     } 

     public function error(){ 
      return $this->_error; 
     } 

     public function count(){ 
      return $this->_count; 
     } 

    } 
+3

그 오류 메시지가 쓸모가 없다. DB 클래스 오류 기능을 사용하여 실제 오류 메시지를 가져 오십시오. –

+3

코드의 벽 ... 그러나 여전히 거짓/위증한 값을 반환하는 DB :: _ update()의 정의를 공유하지 않습니다. 주변의 혼란을 줄이고 해당 DB를 추가하십시오 :: _ 업데이트 함수 (및 가능한 종속성). – Wrikken

+0

나는 무지하거나 아무것도 아니에요. 나는 여전히 PHP를 배우고있다. 어떻게해야합니까? 죄송합니다. – Tauciokas

답변

1

유효, 같은 :

UPDATE table SET f1 = ?, f2 = ?, f3 = ?, f4 = ? WHERE userID = {ID} 
,536 :

function update($table, $userID, $fields){ 
     $set = ''; 
     $x = 1; 

     foreach($fields as $name => $value){ 
      $set .= "{$name} = ?"; 

      if($x < count($fields)){ 
       $set .= ', '; 
      } 
      $x++; 
     } 


     $sql = "UPDATE {$table} SET {$set} WHERE userID = {ID}"; 

     return $sql; 
    } 

echo update('table',1,array('f1'=>'v1','f2'=>'v2','f3'=>'v3','f4'=>'v4')); 

결과는 같을 것이다

귀하의 ID은 제가 통과 한 실제 정수가 아닙니다.

하지만 당신이되고 당신의 문을 변경 한 경우 :

//some code 
$sql = "UPDATE {$table} SET {$set} WHERE userID = {$userID}"; 
return $sql; 

결과는 다음과 같습니다

UPDATE table SET f1 = ?, f2 = ?, f3 = ?, f4 = ? WHERE userID = 1 
+0

우수. 아프다. 잠깐만 기다려 봐. – Tauciokas

+0

당신은 절대 전설이다. 정말 고마워 – Tauciokas

관련 문제