Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将php日期时间插入mysql_Php_Mysql - Fatal编程技术网

将php日期时间插入mysql

将php日期时间插入mysql,php,mysql,Php,Mysql,我试图将datetime插入mysql表中的一列中 <?php //Some code date_default_timezone_set('Europe/London'); //Other variables defined also $date_time = new DateTime(); $queryreg = mysql_query (" INSERT INTO users VALUES ('','$username','$password','$email

我试图将datetime插入mysql表中的一列中

 <?php

//Some code

date_default_timezone_set('Europe/London');

//Other variables defined also

$date_time = new DateTime();


$queryreg = mysql_query ("

    INSERT INTO users VALUES ('','$username','$password','$email','$website','$image','$date_time')

    ");



?>

这是因为您正试图在SQL查询中将$date\u time用“”括起来,从而将其键入字符串。删除周围的引号或通过执行以下操作将其转换为字符串:

$date_time->format('Y-m-d H:i:s');

您必须使用
$datetime->format('Y-m-dh:i:s')
进行插入,如下所示:

INSERT INTO users VALUES ('', '$username', '$password', '$email', '$website', '$image', '{$date_time->format('Y-m-d H:i:s')}')
<?php
//Some code
date_default_timezone_set('Europe/London');

//Other variables defined also
$date_time = new DateTime();

$queryreg = mysql_query("INSERT INTO users VALUES
      ('','$username','$password','$email','$website','$image',
      '{$date_time->format('Y-m-d H:i:s')}')");
?>
我还建议不要使用
mysql.*
函数,而是要学习使用
PDO
和准备好的语句,或者至少是
mysqli.*
函数


还要清理输入以防止SQL注入。

最好的解决方案是在表中使用默认值CURRENT\u timestamp的timestamp字段

但如果要手动控制此对象,则需要将DateTime对象转换为如下字符串:

INSERT INTO users VALUES ('', '$username', '$password', '$email', '$website', '$image', '{$date_time->format('Y-m-d H:i:s')}')
<?php
//Some code
date_default_timezone_set('Europe/London');

//Other variables defined also
$date_time = new DateTime();

$queryreg = mysql_query("INSERT INTO users VALUES
      ('','$username','$password','$email','$website','$image',
      '{$date_time->format('Y-m-d H:i:s')}')");
?>

为日期提供字符串格式,如下所示:

INSERT INTO users VALUES ('', '$username', '$password', '$email', '$website', '$image', '{$date_time->format('Y-m-d H:i:s')}')
<?php
//Some code
date_default_timezone_set('Europe/London');

//Other variables defined also
$date_time = new DateTime();

$queryreg = mysql_query("INSERT INTO users VALUES
      ('','$username','$password','$email','$website','$image',
      '{$date_time->format('Y-m-d H:i:s')}')");
?>
日期格式(变量,“字符串格式”)

日期格式($date\u time,“%m/%d/%y”),例如。

可能重复的