这是我的表:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`mail` varchar(50) NOT NULL UNIQUE,
`password` varchar(30) NOT NULL,
`reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
这是我在php代码中的查询:
$query = "INSERT INTO `users` (`email`,`psw`) VALUES ('".$email."','".$psw."')";
$_SESSION["id"] = mysqli_insert_id($db_con);
// get the date of this row and put it in $_SESSION["regdate"]
答案 0 :(得分:1)
您只需使用mysqli_insert_id
并选择已插入的行
$query = "INSERT INTO `users` (`email`,`psw`) VALUES ('".$email."','".$psw."')";
mysqli_query($db_con, $query);
$_SESSION["id"] = mysqli_insert_id($db_con);
$query = "SELECT reg_date FROM `users` WHERE id='{$_SESSION["id"]}'";
$result = mysqli_query($db_con, $query);
$row = mysqli_fetch_array($result);
print_r($row);
或者您可以插入当前日期时间,这样您就不必再次查询以获取时间戳。
$dt = date('Y-m-d H:i:s');
$query = "INSERT INTO `users` (`email`,`psw`, reg_date) VALUES ('".$email."','".$psw."', '".$dt."')";
mysqli_query($db_con, $query);
echo $dt; // last date you have inserted.
答案 1 :(得分:1)
是的,有。稍微更改插入语句:
$currentDate=date("Y-m-d H:i:s");//Get current date
$query = "INSERT INTO `users` (`email`,`psw`,`reg_date`) VALUES ('".$email."','".$psw."', '.$currentDate.')";//Save date, email and password to database
$_SESSION["id"] = mysqli_insert_id($db_con);//Get ID of the last row
$_SESSION["regdate"] = $currentDate;//Save it in session
虽然您正在搜索如何在数据库和$_SESSION
数组中插入当前日期,但您遇到了更大的问题。您的insert语句容易受到SQL注入攻击,这意味着您的应用程序存在安全问题。而不是使用字符串连接,使用PDO
类和所谓的预准备语句。
示例:
$currentDate=date("Y-m-d H:i:s");//Get current date
$sql = "INSERT INTO users SET email=?, psw=?, reg_date = ?";
$q = $conn->prepare($sql);
$q->execute(array($email, $psw, $currentDate));
$_SESSION["id"] = mysqli_insert_id($db_con);//Get ID of the last row
$_SESSION["regdate"] = $currentDate;//Save it in session
它会起作用:))
答案 2 :(得分:0)
只需在插入后运行查询即可获取日期
query = "SELECT `reg_date` FROM `users` WHERE `id` = $_SESSION["id"]"
答案 3 :(得分:0)
获取最后插入行的ID
$last_id = mysqli_insert_id($db_con);
然后,执行选择查询
select reg_date from users where id = $last_id;
答案 4 :(得分:0)
你可以这样做,确保id应该是自动增量
SELECT reg_date FROM users ORDER BY id DESC LIMIT 0,1