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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用