用于插入 PHP 的时间戳


timestamp for inserting in php

我有这个sql查询,我需要在更新的上一个函数中为名为"created"的字段添加时间戳。我添加了$sqlMod = sprintf("UPDATE %s SET last_modified=now(), %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);它工作得很好。但是,我似乎无法在插入函数中正确使用该语法以使其正常工作。我试过(created, %s) VALUES ("now(), %s")...而且它不起作用。

$sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")', $table, implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('",  "',array_map('mysql_escape_string', $values)));

目前: INSERT INTO projects (created, project_name, project_bold, project_content, id) VALUES ("now(), something", "something", "something", "46919705")

NOW()的调用不应该在引号内,但后面的参数应该被引用。

(created, %s) VALUES (now(), "%s")

不要使用mysql_escape_string() .请改用更全面的mysql_real_escape_string()。从长远来看,考虑切换到支持MySQLi或PDO等预准备语句的API,尽管您仍然需要像您正在做的那样连接动态SQL的表名。

虽然MySQL支持双引号,但字符串值的单引号更标准一些。交换字符串上的报价并implode()调用,因此最终产品如下所示:

$sql = sprintf("INSERT INTO %s (created, %s) VALUES (NOW(), '%s')", $table, implode(', ', array_map('mysql_real_escape_string', array_keys($values))), implode("',  '",array_map('mysql_real_escape_string', $values)));

作为您和未来读者关于安全性的最后一点,我们看不到 $table 的起源,但如果它源自任何类型的用户输入,建议根据可接受的表名称白名单检查其值,因为它无法得到mysql_real_escape_string()的充分保护。

您似乎将所有参数放入一个字符串中 - 这是行不通的,因为每个参数都需要是一个单独的实体。

您可能只使用TIMESTAMP DEFAULT CURRENT_TIMESTAMP,并让数据库为您输入创建时间。

$values数组中删除created并将其硬编码在 SQL 字符串中。

$sql = sprintf('INSERT INTO %s (%s, created) VALUES ("%s", now())', $table, implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('",  "',array_map('mysql_escape_string', $values)));