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")
The call to
NOW()should not be inside quotes, but the arguments that follow it should be quoted.Don’t use
mysql_escape_string(). Use the more comprehensivemysql_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: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 bymysql_real_escape_string().