MySQL y PHP-insertar NULL en lugar de una cadena vacía


Tengo una instrucción MySQL que inserta algunas variables en la base de datos. Recientemente he añadido 2 campos que son opcionales (int intLat, int intLng). Ahora, si estos valores no son entró pasar una cadena vacía como valor. ¿Cómo paso un valor NULL explícito a MySQL (si está vacío)?

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  '$intLat', '$intLng')";
mysql_query($query);
Author: philomath, 2011-01-07

9 answers

Para pasar un NULL a MySQL, se hace precisamente eso.

INSERT INTO table (field,field2) VALUES (NULL,3)

Por lo tanto, en su código, marque if $intLat, $intLng are empty, si lo son, use NULL en lugar de '$intLat' o '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";
 110
Author: Rocket Hazmat,
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-05-11 11:00:48

Si no pasa valores, obtendrá nulos para los valores predeterminados.

Pero puedes pasar la palabra NULL sin comillas.

 10
Author: dkretz,
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
2011-01-06 22:04:08

Todo lo que tienes que hacer es: $variable =NULL; / / y pasarlo en la consulta insert. Esto almacenará el valor como NULL en mysql db

 6
Author: Shahid Sarwar,
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
2016-06-09 08:24:09

Esto funciona muy bien para mí:

INSERT INTO table VALUES ('', NULLIF('$date',''))

(primer campo id de incrementos '')

 5
Author: Jesenko Sokoljak,
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
2018-04-20 09:28:53

Normalmente, se agregan valores regulares a MySQL, desde PHP de la siguiente manera:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
    $result = mysql_query($query);
    db_close(); // just some code to close the DB
}

Cuando sus valores están vacíos / null (val val1=="" o NULL val1 = = NULL), y desea que se agregue NULL a SQL y no 0 o cadena vacía, a lo siguiente:

function addValues($val1, $val2) {
    db_open(); // just some code ot open the DB 
    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
        (($val1=='')?"NULL":("'".$val1."'")) . ", ".
        (($val2=='')?"NULL":("'".$val2."'")) . 
        ")";
    $result = mysql_query($query);
    db_close(); // just some code to close the DB
}

Tenga en cuenta que null se debe agregar como "NULL" y no como "'NULL'" . Los valores no nulos deben añadirse como "'".$val1."'", sucesivamente.

Espero que esto ayude, solo tuve que usar esto para algunos registradores de datos de hardware, algunos de ellos recolectando temperatura y radiación, otras solo radiación. Para aquellos sin el sensor de temperatura necesitaba NULL y no 0, por razones obvias (0 es un valor de temperatura aceptado también).

 3
Author: radhoo,
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-10-10 14:32:17

Su consulta puede ir de la siguiente manera:

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
      VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);
 2
Author: sikas,
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-15 20:23:59

Compruebe las variables antes de construir la consulta, si están vacías, cámbielas a la cadena NULL

 1
Author: profitphp,
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
2011-01-06 22:04:09

Puedes hacerlo por ejemplo con

UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'
 1
Author: bernte,
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-08-02 14:59:16

Por alguna razón, la solución de Radhoo no funcionaría para mí. Cuando usé la siguiente expresión:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (con comillas) se insertó en lugar de null sin comillas, convirtiéndolo en una cadena en lugar de un entero. Así que finalmente lo intenté:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

El espacio en blanco resultó en que el null correcto (sin comillas) se insertara en la consulta.

 1
Author: bobv,
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-03-08 09:18:20