2014-04-23 5 views
0

나는 사용자라는 클래스가 있습니다. 나는 이러한 모든 기능을 데이터베이스 '수퍼 객체'로 옮길 수 있도록 일반적인 데이터베이스 메소드를 추상화하려고 노력 중이다.클래스 메서드의 추상화가 작동하지 않는 데이터베이스와의 상호 작용

class User { 

     protected static $table_name="users"; 
     protected static $db_fields = array('id', 'first_name'); 

     public $id; 
     public $first_name; 


    public function create() { 
    global $database; 
    $attributes = $this->sanitized_attributes(); 
    $sql = "INSERT INTO ".self::$table_name." ("; 
    $sql .= join(", ", array_keys($attributes)); 
    $sql .= ") VALUES ('"; 
    $sql .= join("', '", array_values($attributes)); 
    $sql .= "')"; 
    if($database->query($sql)) { 
    $this->id = $database->insert_id(); 
    return true; 
    } else { 
    return false; 
    } 
    } 
    } 

이것은 내가 만든 메소드에서 클래스에 무관심하게 만들었습니다. 보시다시피, 정말 간단합니다 - 단지 두 개의 데이터베이스 필드 first name과 id. 이 ID는 NULL이 아니고 자동 증가로 설정됩니다. 내 문제는 ...... ......

$ database-> insert_id() 메소드는이 연결을 통해 데이터베이스에 생성 된 마지막 ID를 가져옵니다.

내가

$user = new User(); 
$user->first_name = "Paul"; 
$user->create(); 

내가 얻을를 다음과 같이 간단한

Database query failed: Incorrect integer value: '' for column 'id' at row 1 

Last SQL query: INSERT INTO test_user (id, first_name) VALUES ('', 'Paul') 

... 만들어 실행하면 $ SQL 문이 최대한 멀리 볼 수 정확합니다. ID가 설정되어 있지 않지만 자동 증가로 설정된 것이 자동으로 설정되어서는 안되는 문제가 있음을 이해합니다 .....

또한 ... PDO가 갈 방법은 알고 있지만 지금 (그리고 나는 점진적으로 그것을 배우고있다.), 누군가가 나를 도와 줄 수 있었는지 ...

+0

'SQL은 PHP가 아니며' '은 PHP에서 null로 평가되지만 SQL에서는 그렇지 않습니다. SQL에서는 빈 문자열입니다. – Gervs

답변

0

함수를 사용자 정의했다. 위의 시나리오에서 작동합니다.

public function create() { 

    global $database; 

    foreach($this->sanitized_attributes() as $key=>$attribute) { 
     if ((is_null($attribute)) || empty($attribute)) { 
      $attributes[$key] = "null"; 
     } else { 
      $attributes[$key] = "'" . $attribute . "'"; 
     } 
    } 
    $sql = "INSERT INTO ".self::$table_name." ("; 
    $sql .= join(", ", array_keys($attributes)); 
    $sql .= ") VALUES ("; 
    $sql .= join(", ", array_values($attributes)); 
    $sql .= ")"; 
    if($database->query($sql)) { 
    $this->id = $database->insert_id(); 
    return true; 
    } else { 
    return false; 
    } 
}