(Not an answer to your actual question but maybe to your problem. The "immediate" problem regarding the variable substitution in your double-quoted string has been answered here)
Since you're already using prepare you can simply make it a parametrized statement
$insert = $db->prepare('insert into mytable set mycolumn=?' ); $insert->execute( array($variable) );
and $variable===NULL will result in a NULL value in your MySQL table.
e.g.
<?php $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array( PDO::ATTR_EMULATE_PREPARES=>false, PDO::MYSQL_ATTR_DIRECT_QUERY=>false, PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION )); setup($pdo); $stmt = $pdo->prepare('INSERT INTO soFoo SET mycolumn=?'); $variable = 1; $stmt->execute( array($variable) ); $variable = NULL; $stmt->execute( array($variable) ); $variable = 2; $stmt->execute( array($variable) ); foreach( $pdo->query('SELECT id,mycolumn FROM soFoo', PDO::FETCH_ASSOC) as $row) { var_export($row); } function setup($pdo) { $pdo->exec(' CREATE TEMPORARY TABLE soFoo ( id int auto_increment, mycolumn int, primary key(id) ) '); }
prints
array ( 'id' => 1, 'mycolumn' => 1, )array ( 'id' => 2, 'mycolumn' => NULL, )array ( 'id' => 3, 'mycolumn' => 2, )
$variableis converted to an empty string => SQL error. You should be using prepared statements.set mycolumn = ;, with no value. if you want a php null to become an sql null, you have toif ($var === null) { $var = 'null'; }convert it to a STRING with the charsn,u,l,lPDO::PARAM_NULLshould do the trick : php.net/manual/en/pdo.constants.php - so while PHP'snullis not necessarily the same as MySQLs you can use it to ensure you're insertingNULLinto the DB when your PHP value isnull