I am creating a simple query in mySql to insert some values from a form into my db.
My question is simple, but in reference to the difference between binding variables vs specifying them into the sql statement.
Binding:
$query = "INSERT INTO test (name, lastName, price) VALUES (:name, :lastName, :price)";
$apply = $con -> prepare($query);
$apply -> execute (array(':name'=>$name,':lastName'=>$lastName,':price=>$price'));
Typical:
$query = "INSERT INTO test (name, lastName, price) VALUES ($name, $lastName, $price)";
Execute the query....
Is the Binding option really recommended even for simple cases as the one above? Why is that?
Thanks!
Although you can have your query perfectly safe without binding (by formatting all variables manually), using prepared statements to represent your data in the query is indeed the only proper way.
The importance of using prepared statements is often misjudged, so, I'd like to clarify the real benefits:
Because it is more secure.
If the three variables are populated with user's data, you don't need to sanitize the inputs. Also, if you need to repeat that query multiple times, the overall execution should be faster.
And I personally think that it's easier to read and debug, when you have to read again your queries after a couple of months...
It's necessary since you have user defined values, and they can be easily manipulated by the user, to break your query structure and execute unwanted commands.
It wouldn't be necessary if the data is only manipulated by the server. But since it uses data from the superglobals, which user can manipulate (cookie, session, post, get, request...), it's a must.