php - How to update a date value that is blank on MSSQL?
问题描述
I am creating a form that extracts user info, and the users can update their info if needs be. On the form there are two date fields, the second field is optional. So when the user clicks UPDATE and the second date field is blank, in MSSQL database it updates the date_two field with "01/01/1970". I am using PHP with MSSQL, so in the code I have:
if(isset($_POST['update']) {
$date_two = $_POST['date_two'];
if($date_two == "")
$date_two == NULL;
else
$date_two = date("Y-m-d", strtotime($date_two) );
UPDATE table SET date_two = CAST('$date_two' as DATE2);
}
The resulted entry is 01/01/1970, instead of NULL.
解决方案
你应该检查你的输入日期值是否是一个空字符串('')并管理为空,因为如果你的 var 的值不为空(也是一个空字符串),更新会产生一个日期值
UPDATE table SET date_two = (case when '$date_two' = '' then NULL
else CAST('$date_two' as DATE2)
end);
无论如何,你不应该在你的 sql 命令中使用 php var 你在 rusk 进行 sqlinjection .. 看看你的数据库驱动程序 fior 准备好的命令和绑定参数 ..
推荐阅读
- react-native - 如何用我对本机反应的看法创建一个波浪
- c++ - C++中如何判断一个整数类型是不是内置类型?
- verilog - 移位寄存器,将有线输入连接到内部寄存器
- python - Python,从还包含列表的大型嵌套字典中返回指定的键值
- tomcat - log4j2 错误导致 Tomcat 停止
- airflow - 在多个时区的固定时间安排任务
- angular - 在 Angular Universal 上使用 Facebook 的 SDK 在移动设备中登录的问题
- reactjs - 这是 React 在调用 api、设置状态和渲染数据时的常见模式吗?
- javascript - 对数组进行排序后,useState 不会重新渲染
- point-clouds - 为什么 pcl 中的 PPFRegistration 工作这么慢