Using a Persistent Database Object Connection from Other Objects in PHP

With a prepared statement you set in stone exactly what the query will look like in code written by your hand only. It only lacks the actual data which will be provided on execution.
For example you are doing an insert for two columns.

"INSERT INTO MyTable (this, that) VALUES (:this, :that)"

So it is already decided, before a user can influence anything, that we are going to insert two values into the two named columns in the named table. Nothing more and nothing less.
So there is no way a user can manipulate the query to do something more, like: Insert this and that, then select all the email addresses, then drop the table (or whatever). Because it has already been established that we are doing a single query that inserts two values into the two named columns in the named table and nothing more.
Then you pass over the values on execute, and it happens.

No need to escape, but for a “belt & braces” approach you should still sanitise and validate all user input. But do still encode on output to a page from the database.

Not something you will use every time, but very useful and efficient. Prepared statements are reusable, you send it once and use it over and over any number of times, likely with different values.
For example, prepare a query once, then enter a foreach loop and use the same query for every element in an array.
Or prepare once, then have conditionals that determine the the data passed into the query.

2 Likes