php - MySQL 使用 PHP sprintf 插入到 NULL INT 列

标签 php mysql string-formatting printf

我正在尝试使用 php sprintf 格式化 mysql 插入语句,但这样做会在记录列中插入 0 而不是 NULL .我正在寻找解决此问题的方法,同时仍在使用 sprintf 进行格式化:

$query = sprintf("INSERT INTO `efix_lines`
                     (EventID, Serial, SerialRequired, PartNumber,
                      MfgRev, DefectID, CircuitReference, CreatorID,
                      CreatorName, Created)
                   VALUES (%d, '%s', %d, '%s', '%s', %d, '%s', %d, '%s', '%s')",
                      $oSubmitData['EventID'],
                      EVL($oSubmitData['Serial'], NULL),
                      EVL($oSubmitData['SerialRequired'], NULL),
                      EVL($oSubmitData['PartNumber'], NULL),
                      EVL($oSubmitData['MfgRev'], NULL),
                      EVL($oSubmitData['DefectID'], NULL),
                      EVL($oSubmitData['CircuitReference'], NULL),
                      $oSubmitData['CreatorID'],
                      $oSubmitData['CreatorName'],
                      $pDate );

//I made this quick EVL function to help with shorthand ternary operators within my actual syntax
function EVL( $var1, $var2 ){
   return ( empty( $var1 ) ? $var2 : $var1 );
};

当尝试插入 NULL 时,问题出现在 DefectID 列上,因为它是空的。 sprintf 想要按照 %d 的指示插入一个整数,因此它插入 0 而不是 NULL。我能做什么?

最佳答案

您将需要使用 %s,原因是,对于 PHP,null 不是整数的有效值,而对于 MySQL,它完全是(假设该列未声明 NOT NULL)。

你可能想做类似的事情

function NVLint($var) {
  if (empty($var)) return 'NULL';
  else if (!is_numeric(!$var)) return 'NULL';
  else return round($var);
}

... sprintf ...
  NVLint($oSubmitData['DefectID']),

关于php - MySQL 使用 PHP sprintf 插入到 NULL INT 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453714/

相关文章:

PHP 变量在 MySQLi 语句中不起作用

php - mySQL:从多行获取所有位置的值

php - 相同的连接查询: two different results through Phalcon and phpMyAdmin

php - 如何将方括号数组中保存的数据插入数据库?

mysql - 从具有相同 id 的多个表中检索数据

php - 使用 PHP 从远程 JSON 文件检索数据(单个字段)

php - MySQL左连接显示一个表的值但存储在第二个表中

python 更改数字格式 ndarray 许多位

python - 打印大量格式化数据时如何避免 Broken Pipe 错误?

c# - 带有 SQL 通配符的 String.Format 导致 Dapper 查询中断