php PDO::PARAM 日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2374631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDO::PARAM for dates?
提问by vitto
Does some PDO::PARAM_???exist which can be used for dates or timestamps?
是否PDO::PARAM_???存在可用于日期或时间戳的一些?
Sample code:
示例代码:
$sql = "UPDATE my_table SET current_date = :date WHERE id = 43";
$statement = $pdo->prepare ($sql);
$statement->bindParam (":date", strtotime (date ("Y-m-d H:i:s")), PDO::PARAM_STR);
$statement->execute ();
回答by Pascal MARTIN
When writing a date in an SQL query, you are writing it as a string; you have to do the same with prepared statements, and use PDO::PARAM_STR, like you did in the portion of code you proposed.
在 SQL 查询中写入日期时,您将其写入为字符串;你必须对准备好的语句做同样的事情,并使用PDO::PARAM_STR,就像你在你提出的代码部分所做的那样。
And for the "timestamp", if by "timestamp" you mean:
对于“时间戳”,如果“时间戳”是指:
- The MySQL timestamp data-type: it's the same, you'll pass it as a
string - The PHP Unix timestamp, which is an integer: you'll pass it an
int.
- MySQL 时间戳数据类型:相同,您将其作为
string - PHP Unix 时间戳,它是一个整数:您将传递给它一个
int.
回答by Rolty
Simply creating the date using php date function should fix this issue for you.
简单地使用 php date 函数创建日期应该可以为您解决这个问题。
$handle->execute(array(":date"=>date("Y-m-d H:i:s", strtotime($date)), PDO::PARAM_STR));
Edit: Please note though, that
strtotime(http://php.net/manual/en/function.strtotime.php) can't handle every kind of date formats.
编辑:但请注意,
strtotime(http://php.net/manual/en/function.strtotime.php)无法处理所有类型的日期格式。
回答by Your Common Sense
Nope. Treat date as a string.
不。将日期视为字符串。
回答by Diego Andrade
You have to treat the date as string, but you can create a function to check if is a valid date before pass it as a param. Like this:
您必须将日期视为字符串,但您可以创建一个函数来检查是否为有效日期,然后再将其作为参数传递。像这样:
function checkValidDate($date, $format = "dd-mm-yyyy"){
if($format === "dd-mm-yyyy"){
$day = (int) substr($date,0,2);
$month = (int) substr($date, 3,2);
$year = (int) substr($date, 6,4);
}else if($format === "yyyy-mm-dd"){
$day = (int) substr($date,8,2);
$month = (int) substr($date, 5,2);
$year = (int) substr($date, 0,4);
}
return checkdate($month, $day, $year);
}
回答by hector teran
This worked for me.
这对我有用。
//MS SQL
$sql = "UPDATE my_table SET current_date = GETDATE() WHERE id = 43";
$statement = $pdo->prepare ($sql);
//$statement->bindParam (":date", strtotime (date ("Y-m-d H:i:s")), PDO::PARAM_STR);
$statement->execute ();

