When inserting free text into a MySQL DB through a form I want to escape characters such as ’ or " or / etc. I have tried using this coding in my ‘INSERT INTO TABLE SET’ command but it doesn’t work:
Yeah, thanks hash, I didnt really use PDO much, but you have spurred me to get back into it, and it’s quite a damn nice way of doing things, so ta goes to you!
// the connection
$db = new PDO("mysql:host=localhost;dbname=db", 'root', 'secret');
// regular query, $st is a statement object returned containing results
$st = $db->query("SELECT * FROM table WHERE field = ".$dangerous);
// $st is now a prepared statement, values will be bound later
$st = $db->prepare("SELECT * FROM table WHERE field = ?");
// bind values and execute, no need to escape as the data is separated
$st->execute(array($no_longer_dangerous));
Thank you [COLOR=#336633][B]ScallioXTX[/B][/COLOR] that is exactly what I needed to make it work, but as a separate statement not as part of the INSERT command.
Why create your own solution that may contain security holes when there is a built in function specifically for the purpose.
If you are using mysql_query or mysqli_query then you need to use mysql_real_escape_string or mysqli_real_escape_string respectively on each individual field before inserting them into the query so that their content will not get confused with the query itself. A better alternative is to use a prepare statement with either mysql/PDO or mysqli to keep the data completely separate from the query.