For what is needed Prepare in PDO PHP? Explain simply a new language.
Answer 1, Authority 100%
Very good question.
First, for correct data formatting.
Here there is a good explanation , but it is in English.
If short, any data that falls into the query must be correctly formatted. Otherwise, they will be able to cause a mistake or worse – vulnerability.
and you need to format the data must be necessary before the execution of the query – not earlier. Therefore, the driver to work with the database itself should be formatted, in this case – PDO.
When we send a request to
Prepare () , we substitute special markers to the place of the data substrate. And the data itself transmit after, in
execute () .
After performing the request, PDO substitutes the data into the place of markers, correctly formatting them. And thus, in the query, there will never be a syntax error caused by data, no – the more – injections.
Prepare () / Execute () You must always use if at least one variable is used in the query.
Note. Methods for correct data formatting can be different. In particular, depending on the settings, the PDO may not substitute the formatted data immediately into the request, but send them separately. In this case, when calling
Prepare () , the request together with markers is sent to the database, and the data is driven separately from it, after calling
Execute () . In this embodiment, the data at all does not intersect in any way with the request, and fall straight into the database. The principle of another, but the essence is one – no syntax error.
Secondly, to save resources when performing the same requests.
Also during separate dispatch, you can save server resources slightly. In this mode, you can call
Prepare () just once, and then only send data via
execute () . Thus, the server will have to pass the request only once that slightly reduces the total query execution time. But special miracles of increasing productivity from this way should not be waiting for.
Enter the data to the request immediately or send separately, PDO decides depending on the
PDO :: ATTR_EMULATE_PREPARES .