Say we have a typical prepared statement query like so:
$db->query("SELECT * FROM users WHERE id = :id");
$db->bind(':id', "x ' OR 'x' = 'x");
$db->execute();
Question
What is the mechanism that works behind the scenes to ensure SQL injection is avoided?
Namely, I understand that SQL and Data have to be merged back at some point for data retrieval process to work. What is the mechanism of this merge, and which subsystem is responsible for the merge?
Program & Data Separation
I hear and it has been noted that the inherent separation between Program
and Data
remove the possibility of such and injection. This is not getting to me because I can write a program that simply joins SQL & Data back together.
To drive the point home, here's some code to illustrate this point.
//receive SQL statement and data *separately*
function setSQL($sql) {$this->sql = $sql;}
function setData($data) {$this->data = $data;}
function executeStatement()
{
//simplified code that shows that we can
//blindly replace named parameter with supplied
//data inside SQL and execute it
db_execute(str_replace(':id', $this->data, $this->sql));
}
Are we protected? Well, do we have a program? yes. Do we have the Data sent separately? yes... do we still have injection attack? yes....? did I miss something? The part I am missing is at the heart of the question.
Data has to be joined with the SQL or the Program somehow, and I seek to find how it is done at code/pseudocode level, and what subsystem is responsible for merging this data together.
I am looking for "Fill in this gap in my knowledge" type of answer, where the mechanism of joining data back is exposed enough to cover up this gap.