在mysql中用php更新值NULL

时间:2012-06-21 09:10:57

标签: php mysql 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

我想用php将parent_id设置为NULL,但是我该如何做呢? 这些都是错的:

$term->parent_id = 'NULL'; - >这是一个字符串
$term->parent_id = NULL; - >这是空的 $term->parent_id = 0; - >这是一个整数

2 个答案:

答案 0 :(得分:1)

查询应为:

某些查询编辑器要求NULL为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 :(得分:1)

我的数据库类出现问题,这就是为什么我的parent_id值总是空的 这就是我修复它的方法:

旧代码:

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;
    }