I'm building a website where users can store code snippets, using PHP and a mySQL database. But I can't figure out how to safely insert user inputed code into my database. I can't transform the input with the 'safety' functions I normally use (trim, stripslashes, etc.) because the whole point is that you can view the code as it's inputed in the database. I've looked at my_real_escape_string() but I saw that it does not escape the % and _, which can be used as MySQL wildcards. Does that pose a threat, or can I just use my_real_escape_string? Thanx in advance.
解决方案
Wildcards only take effect when used in SELECT queries and then only when using certain functions. So for inserting the code it will be fine to use mysql_real_escape_string() as they will have no effect.
To make it better I would recommend that you use PHPs PDO so that you can use parameter binding. The following example is from the PHP manual:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>