¿Cómo puedo insertar valores NULOS usando PDO?


Estoy usando este código y estoy más allá de la frustración:

try {
    $dbh = new PDO('mysql:dbname=' . DB . ';host=' . HOST, USER, PASS);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
}
catch(PDOException $e)
{
    ...
}
$stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)');
$stmt->bindParam(':v1', PDO::PARAM_NULL); // --> Here's the problem

PDO::PARAM_NULL, null, '', todos ellos fallan y lanzan este error:

Error fatal : No se puede pasar el parámetro 2 por referencia en /opt/...

Author: hjpotter92, 2009-09-08

7 answers

Solo estoy aprendiendo DOP, pero creo que necesitas usar bindValue, no bindParam

bindParam toma una variable, a reference, y no extrae un valor en el momento de llamar bindParam. Encontré esto en un comentario sobre los documentos de php:

bindValue(':param', null, PDO::PARAM_INT);

EDITAR: P.d. Usted puede estar tentado a hacer esto bindValue(':param', null, PDO::PARAM_NULL); pero no funcionó para todos (gracias a Shaver por informar.)

 123
Author: JasonWoof,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-25 05:35:45

Al usar bindParam() debe pasar una variable, no una constante. Así que antes de esa línea necesitas crear una variable y establecerla en null

$myNull = null;
$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);

Obtendrías el mismo mensaje de error si intentaras:

$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);
 43
Author: Joe Phillips,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-08 03:27:54

Cuando se usan columnas INTEGER (que pueden ser NULL) en MySQL, PDO tiene un comportamiento inesperado.

Si usa $stmt->execute(Array), debe especificar el literal NULL y no puede dar NULL por referencia de variable. Así que esto no funcionará:

// $val is sometimes null, but sometimes an integer
$stmt->execute(array(
    ':param' => $val
));
// will cause the error 'incorrect integer value' when $val == null

Pero esto funcionará:

// $val again is sometimes null, but sometimes an integer
$stmt->execute(array(
    ':param' => isset($val) ? $val : null
));
// no errors, inserts NULL when $val == null, inserts the integer otherwise

Probamos esto en MySQL 5.5.15 con PHP 5.4.1

 26
Author: ChrisF,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-23 13:17:32

Tuve el mismo problema y encontré esta solución trabajando con bindParam:

    bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
 6
Author: user1719210,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 16:34:02

Para aquellos que todavía tienen problemas (no pueden pasar el parámetro 2 por referencia), defina una variable con valor null, no solo pase null a PDO:

bindValue(':param', $n = null, PDO::PARAM_INT);

Espero que esto ayude.

 5
Author: Pedro Guglielmo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-24 18:27:01

Si desea insertar NULL solo cuando el value es empty o '', pero inserte el value cuando esté disponible.

A) Recibe los datos del formulario usando el método POST, y llama a la función insert con esos valores.

insert( $_POST['productId'], // Will be set to NULL if empty    
        $_POST['productName'] ); // Will be to NULL if empty                                

B) Evalúa si un campo no fue llenado por el usuario, e inserta NULL si ese es el caso.

public function insert( $productId, $productName )
{ 
    $sql = "INSERT INTO products (  productId, productName ) 
                VALUES ( :productId, :productName )";

    //IMPORTANT: Repace $db with your PDO instance
    $query = $db->prepare($sql); 

    //Works with INT, FLOAT, ETC.
    $query->bindValue(':productId',  !empty($productId)   ? $productId   : NULL, PDO::PARAM_INT); 

    //Works with strings.
    $query->bindValue(':productName',!empty($productName) ? $productName : NULL, PDO::PARAM_STR);   

    $query->execute();      
}

Por ejemplo, si el usuario no introduce nada en el campo productName del formulario, entonces $productName será SET pero EMPTY. Por lo tanto, es necesario comprobar si es empty(), y si lo es, entonces insértese NULL.

Probado en PHP 5.5.17

Buena suerte,

 3
Author: Arian Acosta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-18 01:28:36

Prueba Esto.

$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null
 0
Author: hector teran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-04 01:11:42