donglugou6652 2012-07-04 01:15
浏览 116
已采纳

在php中插入的时间戳

I have this sql query and I need to add a timestamp to a field named 'created' in a previous function that updates. I added $sqlMod = sprintf("UPDATE %s SET last_modified=now(), %s WHERE id='%s'", $table, $implodeArray, $_POST['id']); which works just fine. However I cant seem to get that syntax correct in the insert into function for it to work properly. I have tried (created, %s) VALUES ("now(), %s")... and it doesnt work.

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

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

  • 写回答

3条回答 默认 最新

  • duanbei3747 2012-07-04 01:24
    关注

    The call to NOW() should not be inside quotes, but the arguments that follow it should be quoted.

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

    Don't use mysql_escape_string(). Use the more comprehensive mysql_real_escape_string() instead. In the long run, think about switching to an API supporting prepared statements like MySQLi or PDO, although you still need to concatenate in table names for dynamic SQL such as you are doing.

    Although MySQL supports double quotes, single quotes for string values are a little more standard. Swap the quoting on your string and implode() call, so the final product looks like:

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

    As a last point on security for you and for future readers, we don't see the origins of $table, but if it originates from any sort of user input, it is advisable to check its value against a whitelist of acceptable table names since it cannot be adequately protected by mysql_real_escape_string().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?