我正在使用mysql和php创建一个用户注册系统,并在用户表中添加了一个名为'date_expires'的列(DATE NOT NULL),以使注册用户的注册日期到期。使用我的表单,用户可以选择他们的注册期。例如:1年,2年,3年。当用户提交表格时,我已经获得了注册期限的价值..就像这样
$registrationPeriod = $_POST['registration_period];
我的问题是如何将带有上述值的过期日期插入到我的用户表中?
我正在尝试将数据插入到用户表中,但却混淆了我如何使用'date_expires'列进行操作。
到目前为止,这是我的代码......
$q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires)
VALUES ('$u', '$e', '$p, '$fn', '$ln', ????????????? )";
希望有人帮我解决这个问题.. 谢谢。
答案 0 :(得分:2)
你可以采取两种方式。
$expireYears = 2;
$expireDate = strtotime("+" . $expireYears . " years");
使用DATE_ADD(NOW(), INTERVAL 2 YEAR)
:
$expireYears = 2;
$q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires)
VALUES ('$u', '$e', '$p, '$fn', '$ln', DATE_ADD(NOW(), INTERVAL $expireYears YEAR))";
答案 1 :(得分:1)
如果您$_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...