简体   繁体   English

如何使用PHP插入查询将当前时间戳插入MySQL数据库

[英]How to insert the current timestamp into MySQL database using a PHP insert query

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 . 这个表是在MySQL中使用phpMyAdmin工具创建的,对于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? 我究竟做错了什么?

What error message are you getting? 您收到了什么错误消息?

I'd guess your actual error is because your php variable isn't wrapped in quotes. 我猜你的实际错误是因为你的php变量没有用引号括起来。 Try this 试试这个

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" .$somename . "'"; 

Your usage of now() is correct. 你对now()的使用是正确的。 However, you need to use one type of quotes around the entire query and another around the values. 但是,您需要在整个查询周围使用一种类型的引号,而在值周围使用另一种类型的引号。

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'";

Forgot to put the variable in the sql statement without quotations. 忘了把变量放在没有引号的sql语句中。

 $update_query = 
      "UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";

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 . "'"; 

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);
}

Instead of NOW() you can use UNIX_TIMESTAMP() also: 您也可以使用UNIX_TIMESTAMP()代替NOW()

$update_query = "UPDATE db.tablename 
                 SET insert_time=UNIX_TIMESTAMP()
                 WHERE username='$somename'";

Difference between UNIX_TIMESTAMP and NOW() in MySQL MySQL中的UNIX_TIMESTAMP和NOW()之间的区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM