如何使用 PHP 插入查询将当前时间戳插入 MySQL 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6075926/
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
How to insert the current timestamp into MySQL database using a PHP insert query
提问by arun nair
In my MySQL database, I have a table with structure
在我的 MySQL 数据库中,我有一个结构表
username - varchar
insert_time - timestamp
This table was created in MySQL using the phpMyAdmin tool and for the insert_time
column, I have mentioned default value as 0000-00-00 00:00:00
.
该表是使用 phpMyAdmin 工具在 MySQL 中创建的,对于该insert_time
列,我提到的默认值为0000-00-00 00:00:00
.
Now the problem is, I have to update this default value with the current timestamp later on, using a PHP script.
现在的问题是,稍后我必须使用 PHP 脚本使用当前时间戳更新此默认值。
I tried doing the following PHP code:
我尝试执行以下 PHP 代码:
$update_query = 'UPDATE db.tablename SET insert_time=now() '.
'WHERE username='.$somename;
When the PHP script is run, it fails, and is unable to insert anything into the database.
当 PHP 脚本运行时,它会失败,并且无法向数据库中插入任何内容。
What am I doing wrong?
我究竟做错了什么?
回答by Ash Burlaczenko
What error message are you getting?
您收到什么错误消息?
I'd guess your actual error is because your php variable isn't wrapped in quotes. Try this
我猜你的实际错误是因为你的 php 变量没有用引号括起来。尝试这个
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" .$somename . "'";
回答by George Cummins
Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.
您对 now() 的使用是正确的。但是,您需要在整个查询周围使用一种类型的引号,在值周围使用另一种类型的引号。
You can modify your query to use double quotes at the beginning and end, and single quotes around $somename
:
您可以修改查询以在开头和结尾使用双引号,并在周围使用单引号$somename
:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";
回答by Kalaivani M
This format is used to get current timestamp and stored in mysql
此格式用于获取当前时间戳并存储在mysql中
$date = date("Y-m-d H:i:s");
$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'";
回答by Laurence Burke
Forgot to put the variable in the sql statement without quotations.
忘记把变量放在不带引号的sql语句中。
$update_query =
"UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";
回答by redux
Don't like any of those solutions.
不喜欢任何这些解决方案。
this is how i do it:
这就是我的做法:
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='"
. sqlEsc($somename) . "' ;";
then i use my own sqlEsc function:
然后我使用我自己的 sqlEsc 函数:
function sqlEsc($val)
{
global $mysqli;
return mysqli_real_escape_string($mysqli, $val);
}
回答by simhumileco
Instead of NOW()
you can use UNIX_TIMESTAMP()
also:
相反的NOW()
,你可以使用UNIX_TIMESTAMP()
也:
$update_query = "UPDATE db.tablename
SET insert_time=UNIX_TIMESTAMP()
WHERE username='$somename'";