如果您$_POST['registration_period']
以1 year, 2 year
...的形式出现,那么您可以最轻松地去除整数值并在 MySQL 中执行日期计算,例如数字NOW() + INTERVAL n YEAR
在哪里n
。
// Extract it from the registration_period
// Since it is formatted as "n years" with a space between,
// we can split the string on the space. list() assigns an array (returned from explode())
// to individual variables. Since we only actually need one of them (the number),
// we can throw away the second (which is the string "years") by just giving list() one variable
// It still needs a placeholder for the second though, hence the extra comma.
list($years,) = explode(" ", $_POST['registration_period']);
// Make sure it is an int to protect against SQL injection...
$years = intval($years);
在您的查询中,将数字替换为VALUES ()
列表中的日期计算:
INSERT INTO users (.......) VALUES (....., (NOW() + INTERVAL $years YEAR));
请考虑切换到支持预处理语句的 API,如 MySQLi 或 PDO。我们只能希望并假设您的所有查询输入变量都已正确清理并过滤了查询当前形式的 SQL 注入。
$u = mysql_real_escape_string($_POST['u']);
$e = mysql_real_escape_string($_POST['e']);
// etc for all query vars...
(更多信息list()