The two are completely unrelated. HTMLPurifier does not address database security at all: it addresses vulnerabilities in your HTML, such as cross-site scripting attacks.
Prepared statements, on the other hand, address the issue of escaping data you send to your database. Now, we’re talking about stopping SQL injection and protection from plain ol’ SQL errors. It’s also more efficient in cases where you use the same query more than once in your script, and mysqli/PDO offers a whole slew of other benefits (transactions, lazy connections, stored procedures, multiple statements, and so forth).
To answer your question, **yes**, you should read up and start using mysqli or PDO in your scripts.
**No**, this doesn’t mean you can “dump” HTMLPurifier, since it serves a different purpose entirely.
When doing database work, I have a quick question. Is it bad form to open the connection once at the top of the page (say before actually loading any content), and then using this connection throughout the script?
Or is it a better idea, for some reason, to open the connection for every query or group of queries.
My thought would be to use the same connection throughout. The reason I ask is because many tutorials show opening a connection for each statement, but that is probably just to show code-completeness I assume.
That’s a very good question. I tend to open the connection right before I begin my first query, then close it after the last one. I figured opening a new connection for each operation would increase server processes, but I’ve never actually verified if that would be the case.
I’ve spoken to a few guys who code backend apps and they all have said they don’t bother closing anything and have never run into problems.
I just started using PDO, and I set my connection object to NULL when I destroy the class I use to connect to the db. I’ve read elsewhere online that it’s how you deal with PDO connection-closing. I could be ignorant and wrong!
Yes, you should reuse a single DB connection throughout your script in most cases, but you should also avoid opening it until you’re sure you’re going to use it.
There are cases where you’re going to use it “no matter what,” but there are also many times when you might not.
(An example might be a login form – your first thought might be “of course, I’ll always need a connection,” but what happens if the user forgets to enter their username? You skip the query and give them an error message. Wasted connection.)