2012-06-21 88 views
0

PHP我有這個疑問:更新NULL值與MySQL的

UPDATE `terms` 
    SET id = '15', 
     taxonomy_id = '1', 
     parent_id = NULL, 
     level = 0, 
     position = 1, 
     active = '1', 
     time_created = '2012-05-24 09:31:12', 
     time_updated = '0000-00-00 00:00:00' 
WHERE id = 15 

我想設置的PARENT_ID與PHP的NULL,但我要如何做到這一點?
這些都是錯誤的:

$term->parent_id = 'NULL'; - >這是一個字符串
$term->parent_id = NULL; - >這是空
$term->parent_id = 0; - >這是一個整數

+0

PHP代碼和數據庫之間有什麼?即這些值是如何內插的? – symcbean

+0

查詢有什麼問題? 'parent_id = NULL'會將該字段更新爲null。 –

+0

該查詢是正確的,但我想設置一個變量的值,其間的代碼並不是那麼簡單,它是用類構建的 – Ruben

回答

1

有我的數據庫類的問題,這就是爲什麼我PARENT_ID pH值總是空
這是我的固定它:

舊代碼:

public function set($data) 
    { 
     $this->query .= ' SET '; 

     if(is_object($data)) 
      $data = get_object_vars($data); 

     if(is_array($data)) 
     { 
      $l = count($data); 
      $t = 1; 
      foreach($data as $k => $v) 
      { 
       $this->query .= $k . ' = ' . ((is_string($v)) ? '\'' . $this->_escape($v) . '\'' : $this->_escape($v)); 
       if($t < $l) 
        $this->query .= ','; 
       $t++; 
      } 
     } 
     else 
     { 
      $this->query .= $data; 
     } 


     return $this; 
    } 

新代碼:

public function set($data) 
    { 
     $this->query .= ' SET '; 

     if(is_object($data)) 
      $data = get_object_vars($data); 

     if(is_array($data)) 
     { 
      $l = count($data); 
      $t = 1; 
      foreach($data as $k => $v) 
      { 
       $this->query .= $k . ' = '; 
       if(is_string($v)) 
       { 
        $this->query .= '\'' . $this->_escape($v) . '\''; 
       } elseif (is_null($v)) { 
        $this->query .= 'NULL'; 

       } else { 
        $this->query .= $this->_escape($v); 
       } 

       if($t < $l) 
        $this->query .= ','; 

       $t++; 
      } 
     } 
     else 
     { 
      $this->query .= $data; 
     } 

     return $this; 
    } 
1

查詢應爲:

一些查詢編輯器要求NULL爲空

UPDATE `terms` SET 
    id = '15', 
    taxonomy_id = '1', 
    parent_id = null, 
    level = 0, 
    position = 1, 
    active = '1', 
    time_created = '2012-05-24 09:31:12', 
    time_updated = '0000-00-00 00:00:00' 
WHERE 
    id = 15 
+1

'NULL'和'null'有什麼區別? –

+0

@johntotetwoo它取決於他的查詢編輯器'MySQL查詢瀏覽器'儘可能簡單null – Sudantha

+0

@Sudantha sql是不區分大小寫的語言。你怎麼說查詢編輯器要求NULL爲空? – Prathap