如何使用 mySQL 通过 PHP 向 INSERT 添加日期和时间戳?

2022-01-09 00:00:00 date insert php mysql

我有一个带有 mySQL 的插入脚本.我需要将创建记录的日期和时间放在add_time"列中.

I have an insert script with mySQL. I need to place the date and time when the record is created in the 'add_time" column.

谁能告诉我如何修改我现有的脚本来做到这一点?我需要单独的 PHP 脚本吗?

Can anyone show me how to modify my existing script to do this? Do I need a separate PHP script?

我希望日期以标准格式显示:09/25/11 6:54 AM

I would like the date to appear in standard formt: 09/25/11 6:54 AM

<?
  $host="XXXXXXXXXXX";
  $username="XXXXXXX";
  $password="XXXXXXX";
  $db_name="naturan8_hero";
  $tbl_name="cartons_added";

  mysql_connect("$host", "$username", "$password") or die("cannot connect");
  mysql_select_db("$db_name")or die("cannot select DB");

  $order = "INSERT INTO cartons_added (
      type,
      part_no,
      add_type,
      add_qty,
      add_ref,
      add_by,
      add_notes
    ) VALUES (
      '$_POST[type]', 
      '$_POST[part_no]', 
      '$_POST[add_type]', 
      '$_POST[add_qty]', 
      '$_POST[add_ref]', 
      '$_POST[add_by]', 
      '$_POST[add_notes]'
    )";

  $result = mysql_query($order);

  if ($result) {
    $part_no = $_REQUEST['part_no'] ;
    $add_qty = $_REQUEST['add_qty'];
    header("location: inv_fc_add_success.php?part_no=" . urlencode($part_no) . "&add_qty=" . urlencode($add_qty));
  }
  else {
    header("location: inv_fc_add_fail.php");
  }
?>

推荐答案

您在数据库中设置了add_time"列吗?是DATETIME格式吗?

You got the "add_time" column set up in your database? Is it of DATETIME format?

在这种情况下,您可以像这样修改您的查询:

In that case you may just modify your query like this:

$order = "INSERT INTO cartons_added (type, part_no, add_type, add_qty, 
  add_ref, add_by, add_notes, add_time)

  VALUES
  ('$_POST[type]', 
  '$_POST[part_no]', 
  '$_POST[add_type]', 
  '$_POST[add_qty]', 
  '$_POST[add_ref]', 
  '$_POST[add_by]', 
  '$_POST[add_notes]',
   NOW())";

尽管您应该知道执行这样的查询是危险的,因为您相信用户只会输入好东西!谷歌SQL 注入"以了解更多信息,mysql_real_escape_string() 也是如此.

Though you should be aware that executing queries like this is dangerous as you trust the user to input only nice things! Google "SQL Injection" to find out more about it, mysql_real_escape_string(), too.

相关文章