Escaping non-text characters

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:

   locationDirections    = 'mysql_real_escape_string($locationDirections)'";

The DB complains about any ’ character contained in the text from $locationDirections. What syntax should I be using?

What syntax should I be using when issuing ‘SELECT FROM TABLE’ to retrieve this field from the DB?

Thanking you in advance for any help.

Best regards,

Glenn.

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! :wink:


// 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.

Best regards,

Glenn.

I am interested to know what “a prepare statement with either mysql/PDO or mysqli” is. Can you elaborate please?

Thank you and regards,

Glenn.

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.

Thanks Hash!

Glenn.

That would be my suggestion as well… especially since prepared queries using PDO auto-sanitize for you.

or you could use:
$whatever = str_replace(“'”, “\'” $whatever);

etc

Where is the dollar sign for indicating it’s a variable? What are those quotes doing in the variable assignment?

It should be:


$locationDirections = mysql_real_escape_string($locationDirections);

:slight_smile: