Escape Characters

The SQL-Parser requires that some characters need to be escaped.
This means putting the backslash character (i.e. \ ) in front of other characters.
This is necessary for double or single quote (i.e. " or ') characters embedded in strings.

If you want to insert the value foo"bar into the column col1, you can't write the following statement:

INSERT INTO personen (col1,col2) VALUES ("foo"bar","bla");

You have to escape the " between foo and bar:

INSERT INTO personen (col1,col2) VALUES ("foo\"bar","bla");

The following charactes must be escaped: (only between ' ' or " "):
' (Single Quote), " (Double Quote), \ (the Backslash itself)

There are 3 different variants to write a SQL Statement in the PHP Code. In each variant the escape character is used differently.
The first variant is the most frequently used and if you have some luck, you never need to escape anything :)

 

Variant 1: Form Fields

If you want to use values of HTML form fields directly in the SQL stataments, you don't need to change anything.
The Content of Form Fields are automaticly correctly escaped .

Example:

$db->executeQuery("INSERT INTO person VALUES('$formField1','$formField2') ");

Variant 2: SQL Statement is between " "

In a Double Quoted String (" ") the following characters must be escaped (PHP rule):

character Escaped

" (Double Quote)

\"
\ (Backslash) \\

But these characters must also be escaped for the SQL-Parser, so you have to escape them twice, because PHP itself will remove one "escaping":

character escaped (for PHP) escaped for the SQL Parser

" (Double Quote)

\" \\\"
\ (Backslash) \\ \\\\
' (Single Quote) ' (no escape char needed between " ") \'

Example:

$db->executeQuery("INSERT INTO person VALUES('double: \\\" ','single: \' '); ");

Variant 3: SQL Statement is between ' '

In a Single Quote String (' ') the following characters must be escaoed (PHP rule):

character Escaped

' (Double Quote)

\'
\ (Backslash) \\

 

But these characters must also be escaped for the SQL-Parser, so you have to escape them twice, because
PHP itself will remove one "escaping":

character Escaped (for PHP) escaped for the SQL Parser

" (Double Quote)

" (no escape char needed between ' ') \"
\ (Backslash) \\ \\\\
' (Singe Quote) \' \\\'

 

$db->executeQuery('INSERT INTO person VALUES("double: \" "," single: \\\' "); ');