2
votes

I read so many articles saying that using prepared statements is very secure and good to prevent SQL injections. I built a few websites without using prepared statements. But after read all those articles, I am thinking to change whole codes using prepared statements.

My Question

Is it necessary to use prepared statements always? or is there any scenario whereby normal statement will be sufficient over prepared statements?

2

2 Answers

5
votes

Non-prepared statements are sufficient if you have an SQL query that is entirely hard-coded, and needs no PHP variables in the SQL.

Here's an example:

$result = $mysqli->query("SELECT * FROM mytable WHERE updated_at > NOW() - INTERVAL 7 DAY");

The query is self-contained. It's just a fixed string, entirely under control of your application. There's no way any untrusted content can affect the query.

If your query needs some variable part, then use query parameters, like this:

$stmt = $mysqli->prepare("SELECT * FROM mytable WHERE updated_at > NOW() - INTERVAL ? DAY");
$stmt->bind_param("i", $number_of_days);
$stmt->execute();

The point of query parameters is to separate potentially untrusted content from the SQL parsing step. By using parameters, the value of the bound variable is not combined with the query until after the SQL has been parsed. Therefore there is no way the bound parameter can affect the logic of the query — the parameter will be limited to act as a single scalar value in the query.

1
votes

Just found out your question and I remembered my good old days. I too found it difficult to implement prepared statements because at the first sight, it feels to easy to code without it. Then at another time, I made a login system using PHP for which I was proud. It felt great though making it completely from scratch. But, I had made a mistake of not using them and then I checked google for how one can bypass login system. The first trick gave me headache as I could now log into my webpage without knowing the Username or Password and just using some characters like '-' and boom I was into my webpage. So i went the whole way back and secured it with parameterized queries and now It's secure. Since, you and me both are beginners, these things will surely give us headache. Also, you are required to use them only when you are accepting something from user input. Else you are good to go. Just look around for other vulnerabilities like XSS etc. These too are dangerous. Good luck