Strictly speaking, the query you show is safe since you have a guarantee that the $id
is only an integer value, and it cannot introduce characters to the SQL query that would cause any mischief.
But the type hinting solution won't work for string
type hints. Even if you type-hint that your function argument must be a string,
function updateWithCurrentTime(PDO $connection, int $id, string $value): void{
$query= "INSERT INTO timetable (id,value) VALUES (${id}, '${value}')"; // UNSAFE
You wonder, does $value
contain any quote characters? Does it contain anything else that would cause mischief? You can't prevent it from being an SQL injection vulnerability just by using a type hint.
So type hinting may be effective when using an int
type, but not a string
type. What about the other types? Hmm, must investigate...
Now you've opened a can of worms. You have to investigate all the types, and try to come up with complete guidelines for which ones are safe to interpolate into SQL and which ones aren't. You have to make these guidelines clear enough so every member of your software developer team can follow them, and can use them during code reviews.
Even if you do write the code perfectly and use the appropriate SQL injection defense method for each type, anyone else reading the code later will be confused. "Why aren't variables combined with SQL queries in the same way in different functions?" They would wonder. Figuring out the reasons would take their time and attention away from doing whatever code maintenance task they were assigned to do. Remember that after you develop this code, it will live on for years, and other software developers need to maintain it. It pays off to make code easy to understand.
Or, you can just use parameters.
SQL query parameters work for all types, and you don't have to rely on type-hinting. They're easy, they're effective, and you can use them consistently.
Please stop trying to find ways to avoid using query parameters.
Let me use an analogy: Suppose you were an electrician instead of a software developer. You heard that electrical wires should be insulated to avoid possibilities of short-circuits. But for some reason you don't feel like dealing with insulated wires.
"I'll just put a shim in between the wires to keep them separated." But the item you use as a shim has to be non-conductive and non-flammable.
What kinds of shims are safe to use? Wood... no. Metal... no. Plastic... depends on the type of plastic. Ceramic... I don't know, have to look it up or something...
Every other electrician would look at you strangely.
"Just use insulated wires, are you trying to burn down this building?"