如何从PHP插入空到Postgres


How to insert null to Postgres from PHP

我一直在做一个项目管理系统,我正在用PHP和PostgreSQL 8.4和模型-视图-控制器进行编码。

为了让你们了解上下文,我将从词根解释(尽可能简短)。

我有一个叫做Actividad的类,它扩展了一个数据库抽象类来执行查询。

    class Actividad extends AbstraccionBD
    {      
    
    /**
     * Constructor de la clase
     *
     * @param String  $nom  Nombre 
     * @param String  $des  Descripción
     * @param String  $fi   Fecha de inicio
     * @param String  $fc   Fecha de culminación
     * @param Float   $pon  Ponderación
     * @param Boolean $crit Crítica
     * @param String  $le   Lugar Ejeucución
     * @param String  $rec  Recursos
     * @param Integer $pe   Presupuesto estimado
     * @param String  $est  Estado
     * @param Integer $cal  Calificación
     * @param Integer $peje Presupuesto ejecutado
     * @param Integer $asis Asistencia
     */
    public function __construct($nom, $des, $fi, $fc, $pon, $crit, $le, $rec, 
                                $pe, $est, $cal, $peje, $asis)
    {
        //Asignamos todos los valores especificados al 
        //objeto
        $this->nombre = $nom;
        $this->descripcion = $des;
        $this->fecha_inicio = $fi;
        $this->fecha_culminacion = $fc;
        $this->ponderación = $pon;
        $this->es_critica = $crit;
        $this->lugar_ejecucion = $le;
        $this->recursos = $rec;
        $this->presupuesto_est = $pe;
        $this->estado = $est;
        $this->calificacion = $cal;
        $this->presupuesto_ejec = $peje;
        $this->asistencia = $asis;
        
    }
    public function insertarObjeto()
    {
        //Construimos el query de inserción de datos en la tabla
        //actividad; nótese que se llama al procedimiento almacenado
        //sga.max_num_actividad(int,int) para determinar el número
        //de la actividad que se esta insertando.
        $this->_query = 
            "INSERT INTO sga.actividades " . 
                "(proyecto, ejec_proyecto, num_actividad, nombre, " . 
                "descripcion, fecha_inicio, fecha_culminacion, " .
                "ponderacion, critica, lugar_ejecucion, recursos, " . 
                "prepuesto_estimado, estado, calificacion, " . 
                "presupuesto_ejecutado, asistencia) " . 
            "VALUES " . 
                "($this->proyecto, $this->ejec_proyecto, " . 
                "sga.max_num_act($this->proyecto, $this->ejec_proyecto) + 1, " . 
                "'$this->nombre', " . 
                "'$this->descripcion', '$this->fecha_inicio', " . 
                "'$this->fecha_culminacion', $this->ponderación, " . 
                "$this->es_critica, '$this->lugar_ejecucion', " . 
                "'$this->recursos', $this->presupuesto_est, " . 
                "'$this->estado', $this->calificacion, " . 
                "$this->presupuesto_ejec, $this->asistencia);";
                
        //Ejecutamos el query de inserción
        $this->ejecutarQuery();
    }

(我被要求保持每行80个字符的项目)

表定义(不考虑FK):

CREATE TABLE sga.actividades
(
    proyecto integer NOT NULL,
    ejec_proyecto integer NOT NULL,
    num_actividad smallint NOT NULL,
    nombre character varying(150),
    descripcion character varying(500),
    fecha_inicio date NOT NULL,
    fecha_culminacion date NOT NULL,
    ponderacion numeric (3,2) NOT NULL DEFAULT 0.00,
    critica boolean NOT NULL DEFAULT FALSE,
    lugar_ejecucion character varying(100),
    recursos character varying(250),
    prepuesto_estimado integer,
    estado sga.estados_actividad NOT NULL, -- Dominio estados_actividad
    calificacion integer,
    presupuesto_ejecutado integer,
    asistencia smallint, 
    CONSTRAINT actividad_pkey
        PRIMARY KEY(proyecto, ejec_proyecto, num_actividad)
);

现在,我要做的是传递来自模型的值,像这样:

    $a = new Actividad('Actividad1','DescA1', '14-07-14','14-07-14',0.00, 
                'false',null,null,0,'ACT',null, null, null);
    //Dont worry im using __set method
    $act->proyecto = 1;
    $act->ejec_proyecto = 1;
    $a->insertarObjeto();        

正如你所看到的,我在构造函数中传递了一些NULL值,因为在DB中这些值可以为null,到目前为止都很酷。

当我尝试运行它时,我得到这个查询:

INSERT INTO sga.actividades 
    (proyecto, ejec_proyecto, 
    num_actividad, nombre, 
    descripcion, fecha_inicio, 
    fecha_culminacion,
    ponderacion, critica, 
    lugar_ejecucion, recursos, 
    prepuesto_estimado, estado, 
    calificacion, presupuesto_ejecutado, 
    asistencia) 
VALUES 
    (1, 1, sga.max_num_act(1, 1) + 1, 
    'Actividad1', 'DescA1', '14-07-14', 
    '14-07-14', 0, false, '', '', 0, 'ACT', , , );

这是我的问题:这个查询将永远不会运行,因为我使用NULL关键字从PHP,当它被转换成一个字符串在"连接疯狂",它保持空(在字符串中没有任何东西),所以Postgres(如预期)发送在(, , ,)部分的语法错误。

我需要用NULL关键字替换那些空字符串(''),以便Postgres识别并正确插入它。

另外,构造函数中传递的一些值在insertarObjeto()函数中被包装成单引号(它们在DB中是character varying)。

并且在Postgres中''NULL是不一样的

我试着修复这个

一种方法是放置(N)个if-else语句,并将正确的语句连接到每个情况(这对于将来的代码维护和系统扩展来说有点难看),像这样:
if(is_null($this->asistencia))
{
    $this->_query .= "null, ";
}
else
{
    $this->_query .= "$this->asistencia, ";
}

这种方法的问题是有太多的属性(我有比这个多得多的类)。

我看到的另一种方法是在构造函数中用单引号括空。这适用于整数(坏的解决方案,我知道),但那些包装在单引号已经在函数将抛出查询'null',这也是错误的,即:

INSERT INTO sga.actividades 
        (proyecto, ejec_proyecto, 
        num_actividad, nombre, 
        descripcion, fecha_inicio, 
        fecha_culminacion,
        ponderacion, critica, 
        lugar_ejecucion, recursos, 
        prepuesto_estimado, estado, 
        calificacion, presupuesto_ejecutado, 
        asistencia) 
    VALUES 
        (1, 1, sga.max_num_act(1, 1) + 1, 
        'Actividad1', 'DescA1', '14-07-14', 
        '14-07-14', 0, false, 'null', 'null', 0, 'ACT', null ,null ,null );

有更好的解决方案吗?除了(n) if-else语句?

两种可能的解决方案:

1。省略列

如果您没有定义列默认值,则默认默认值(sic!)是NULL。您可以省略应该是NULL:

的列。
INSERT INTO sga.actividades 
        (proyecto, ejec_proyecto, 
        num_actividad, nombre, 
        descripcion, fecha_inicio, 
        fecha_culminacion,
        ponderacion, critica, 
        prepuesto_estimado, estado) 
VALUES 
        (1, 1, sga.max_num_act(1, 1) + 1, 
        'Actividad1', 'DescA1', '14-07-14', 
        '14-07-14', 0, false, 0, 'ACT');

当然,如果您更改这里没有提到的列的列默认值,您也会更改此INSERT的结果—这可能是也可能不是理想的。

2。使用预处理语句

那么你可以使用PHP NULL值。无论如何,清理输入并防止可能的SQL注入是一个好主意。

pg_prepare($pg_conn, 'insert1', "INSERT INTO sga.actividades (proyecto, ejec_proyecto, ..., lugar_ejecucion, ...) VALUES ($1, $2, ...)");
pg_exec($pg_conn, 'insert1', array(1, 1, ..., NULL, ...));

关于pg_prepare和pg_execute的更多手册