2011-02-28 4 views
1

나는 꽤 붙어있어 누군가가 나를 도울 수 있기를 바라고 있습니다.인덱싱 된 데이터베이스에 빈 값 삽입 문제

내 MySQL 데이터베이스에 일부 양식 데이터를 삽입하려고합니다. 인덱스를 설정할 때 db가 행을 따라 뭔가를 말하는 것으로 채워지지 않을 것입니다. 외부 키를 제거하면 db가 자식 행을 업데이트 할 수 없습니다. 그러나 외래 키를 제거하면 제대로 작동합니다.

다른 테이블에서 자동 증가 ID를 가져 오는 2 개의 색인 필드를 연결하려고합니다. 인덱싱 된 필드에 값이 없기 때문에 오류가 발생했다고 생각합니다. 제발 누군가 도와 드릴까요 ??? :)

== 업데이트 ==

안녕, 답장 주셔서 감사합니다.

질문을 게시하기 전에 외래 키를 제거했습니다.

좀 더 설명해 보겠습니다. MySQL에서 데이터베이스에 외래 키를 추가 할 때 기본 키 필드를 변경할 수 있으며 해당 인덱스 필드가 자동으로 변경되어 원하는 값과 동일한 값을 제공합니다.

문제는 내 PHP 코드를 사용하여 값을 삽입하려고 할 때 자식 오류를 업데이트 할 수 없습니다. 기본 키의 값을 상속 받기 때문에 unique_id 필드의 값을 선택하지 않았습니다. 여기 내 코드는 내가 할 수있는 것처럼 단순화되어있다.

               <?php //this calls the class productupload and instantiates the function insert_form to insert values into the db. 
$product = new productUpload(); 
$product->insert_form();?> //This calls the insert_form function and inserts info into tables 
                        <?php 
class productUpload extends DatabaseObject{ 

protected static $table_name="itm_details"; 
protected static $db_fields =array('id','unique_id','itm_cat','itm_make','itm_model','itm_desc','itm_cond','itm_date_from','itm_date_to','itm_add_date');  


     public $id; 
     public $unique_id; 
     public $itm_cat; 
     public $itm_make; 
     public $itm_model; 
     public $itm_desc; 
     public $itm_cond; 
     public $itm_date_from; 
     public $itm_date_to; 
     public $itm_add_date; 

제출 된 데이터를 가져 오는 insert_form 함수를 강조합니다. 나는 $ UNIQUE_ID

public function insert_form(){ 
global $database; 
//set the object attributes to the form the parameters 
     if(isset($_POST['submit'])) { 
     $result = array(
     $this->itm_cat =(!empty($_POST['itm_cat'])) ? trim($_POST['itm_cat']) : NULL, 
     $this->itm_make =(!empty($_POST['itm_make'])) ? trim($_POST['itm_make']) : NULL,  
     $this->itm_model = (!empty($_POST['itm_model'])) ? trim($_POST['itm_model']) : NULL,         
     $this->itm_desc =(!empty($_POST['itm_desc'])) ? trim($_POST['itm_desc']) : NULL, 
     $this->itm_cond =(!empty($_POST['itm_cond'])) ? trim($_POST['itm_cond']) : NULL, 
     $this->itm_date_from =(!empty($_POST['itm_date_from'])) ? trim($_POST['itm_date_from']) : NULL, 
     $this->itm_date_to =(!empty($_POST['itm_date_to'])) ? trim($_POST['itm_date_to']) : NULL, 
     $this->itm_add_date = date("Y-m-d H:m:s")); 
//check date is numeric 
     //if(is_numeric($_POST['itm_date_from'])) { 
     //$this->itm_date_from = $_POST['itm_date_from']; 
//}  
//check date is numeric       
     //if(is_numeric($_POST['itm_date_to'])) { 
     //$this->itm_date_to = $_POST['itm_date_to']; 
     //} 
     if($result){ 
     $result = $this->create(); 
     } 
     } 
     } 

// 

에 대한 값을 정의하지 않은 참고 여기에있는 위의 게시 된 데이터를 sanitises하고, DB에 삽입 언급 된 생성 기능입니다.

public function create() { 
     global $database; 
     $attributes = $this->sanitised_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; 
     } 

} 
?> 
+4

[PasteBin] (http://PasteBin.com)에 코드를 붙여넣고 코드 링크로 질문을 편집하십시오. 당신은 당신의 질문을 이해하기 위해 너무 많은 코드를 여기에 가지고 있습니다. –

+0

외래 키를 선언하지 않았습니까? 자, 당신이 얻은 것부터, itm_pic_detail의 ID를 널 (null)을 허용하도록 변경하십시오. 아마 당신을 도울 것입니다 ... – Teson

답변

0

키 제약 조건이 이와 같은 것으로 가정합니다.

ALTER TABLE itm_pic_detail ADD FOREIGN KEY (`unique_id`) REFERENCES itm_pic_detail(`itm_pic_id`) ON DELETE CASCADE ON UPDATE RESTRICT; 

정확하게 이해하면이 새로운 규칙을 위반하는 충돌 레코드가 있음을 나타내는 제약 조건 자체를 추가 할 수 없습니다. 다음 쿼리를 실행하여 쿼리를 식별하고 먼저 수정하십시오.

SELECT id FROM itm_details WHERE unique_id NOT IN (SELECT itm_pic_id FROM itm_pic_detail); 
0

스크립트가 사용중인 사용자가 두 테이블을 모두 액세스 할 수 있는지 확인 했습니까?

$ sql을 반향 출력하고 수동으로 실행할 수 있는지 확인해보십시오. 간단하면서도 오류가 발생하기 쉽습니다.

또한,

function ParseInt($value) { 
    $value = (int)$value; 
    return ($value <= 0) ? 'NULL' : $value; 
} 

$this->itm_cat = ParseInt($_POST['itm_cat']); 

당신은 항상 1부터 시작 ID를 < = 0, 자동 증가 필드가 계획 결코 제공 ... 모든 혼란 트림의 삭제하고 대신이 일을하여 스크립트를 최적화 할 수 있습니다.

또한 $ db_fields를 정리하고 자동화 할 수 있습니다.

/* get the columns from the table */ 
function __construct($db, $table) { 
    $this->db  = $db; 
    $this->table = $table; 
    $this->dbfields = array(); 

    $rs = mysqli_query($db, 'SHOW COLUMNS FROM `' . $this->table . '`'); 
    while($row = mysqli_fetch_assoc($rs)) 
    $this->dbfields[] = $row['Field']; 
} 

는 부모 클래스에서, 당신은 한 단계 더 갈 수 있으며, 또한 부모 클래스에이를 추가, 그래서 당신은 열 이름에 체크 정신을 얻을 넣습니다.

function __set($member, $value) { 
    if (!in_array($member, $this->dbfields)) 
    throw new Exception('The table ' . $this->table . ' does not have a column named ' . $member); 
    $this->$member = $value; 
} 

function __get($member) { 
    if (!in_array($member, $this->dbfields)) 
    throw new Exception('The table ' . $this->table . ' does not have a column named ' . $member); 
    return $this->$member; 
} 
관련 문제