Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialShon Levi
6,036 PointsWhat's the use of prepare?
Can someone please help me understand what is the use of 'prepare' against 'query'? What are the differences between those two:
1. $var = something; $results = $db->query('SELECT * FROM myTable WHERE film_id = ' .$var);
2. $var = something; $results = $db->prepare('SELECT * FROM film WHERE film_id = ?'); $results->bindParam(1, $var); $results->execute();
3 Answers
thomascawthorn
22,986 Points- If I use _GET how and restored it in the $var - how does it prevent injections? it's look the same thing
You're using PDO - a database wrapper that has a lot of built in functionality. Part of this functionality includes escaping bound variables. PDO won't escape whole queries, which is why appending raw input to the query string will leave to open to security holes.
- If it prevent injections and so usefull for runs queries why should I use QUERY and not use PREPARE all the time?
You won't always be running queries that rely on internal/external input. In this situations, you could just execute the query straight away.
Hope this helps!
Tom
Shon Levi
6,036 PointsThanks for the fast response!
- If I use _GET how and restored it in the $var - how does it prevent injections? it's look the same thing
- If it prevent injections and so usefull for runs queries why should I use QUERY and not use PREPARE all the time?
John Valera
14,416 PointsUsing prepared statements prevent SQL injections.
It also allows a query to only be parsed once and executed multiple times which speeds up query execution of the same query.
This page shows the benefits of prepared statements: http://php.net/manual/en/pdo.prepared-statements.php