OP 在评论中声明:
虽然问题仍然存在,但两列默认设置为 NULL
这是因为您将一个空值传递给 SQL,因为您的 SQL 的编写方式,它预计值,即使您没有要插入的值。
所以;这是一个重写,仅在 INSERT 不为空时才向 INSERT 添加值(或者您可以增加特异性*并在它们不是 null 时设置)
注意:
此代码仅用于说明,可能不应该按原样使用,因为它可能从原始代码继承了多个安全问题。在完美的世界中,我建议您重写整个代码库以使用 try..catch 块并使用 MySQL Transactions 和 Prepared Statements(更多关于 ;-) 的内容)。
$insert = []; //make array
$insert['post'] = $post;
$insert['datetime'] = $datetimeOG;
$insert['name'] = $name;
$insert['img_dir'] = $img_dir;
// Now, we have an array of VALUEs and the KEYs are the column names.
// So let's remove the 'empty' values.
$insert = array_filter($insert);
*注意:
这包括空格、零和“假”值,因此您需要调整到
您自己的确切要求。
有关如何执行此操作的更多信息,请参阅linked question。
参考 - Removing empty array elements
安全旁注:
在这个问题上你的 SQL / PHP 的安全性有很多问题,远远超出了这个深夜答案的范围,但最重要的是$table 变量。
如果这个$table 变量总是相同的值,它不应该是一个变量并且应该是硬编码的。然后你可以使用Prepared Statements。
如果表变量来自候选名单,则应将其列入白名单,通常使用switch 语句或类似语句。
如果 tavble 变量来自 long 列表,那么您可以使用 REGEX 删除任何讨厌的东西,例如,我将这样做,因为我不知道您的数据是什么样的喜欢:
// remove all non a-z or _ - characters.
$table = preg_replace('/[^a-z_-]/i','',$table);
参考 - How to Insert into MySQL using Perpared Statements
魔法内爆!
数组是神奇的实体。他们可以be imploded(像猴子,但头发和血少)。
所以;我们有$insert 数组和$sql 字符串;
这可以完美地重新组合,甚至在不知不觉中,您将成为大使馆舞会的美女;我的意思是,呃,是的,它会起作用的。
// The column string is made from the array keys
$columns = implode(",",array_flip($insert));
// Be careful to note the quotes...
$values = "'".implode("','", $insert )."'";
创建最终结果.....
所以,让我们把它总结一下吧!
$insert = []; //make array
$insert['post'] = $post;
$insert['datetime'] = $datetimeOG;
$insert['name'] = $name;
$insert['img_dir'] = $img_dir;
$insert = array_filter($insert);
/***
* Check just in case....
***/
if(count($insert) > 0 ){
$cleanedTableName = preg_replace('/[^a-z_-]/i','',$table);
$columns = implode(",",array_flip($insert));
// Be careful to note the quotes...
$values = "'".implode("','", $insert )."'";
$sql = INSERT INTO ". $cleanedTableName." (".$columns.") VALUES (".$values.")";
$mysqli->query($sql) or
error_log("You have an SQL Error! (NEVER output your error to screen): ".$mysqli->error);
}
华丽。我要去泡茶了。
See it in action!!!