Many of the more mature databases support the concept of prepared
statements. actually they can be thought of as a kind of compiled
template for the SQL that an application wants to run, that can be customized
using variable parameters.
Prepared statements offer two major benefits:
- The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
- The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
Prepared statements are so useful that they are the only feature that PDO
will emulate for drivers that don't support them. This ensures that an
application will be able to use the same data access paradigm regardless of
the capabilities of the database.
Example--
<?php
$your_stmt = $obj_pdo->prepare("INSERT INTO table_name (field1, field2) VALUES (:field1, :field2)");$your_stmt->bindParam(':field1', $name);$your_stmt->bindParam(':field2', $value);
// insert one row$name = 'ABC';$value = 10;$your_stmt->execute();// insert another row with different values$name = 'XYZ';$value = 30;$your_stmt->execute();?> Here we are executing execute statement 2 times while prepare statement only once.
$obj_pdo->prepare() to prepare a query to know the database that something is going to be executed.$your_stmt->bindParam(':field1', $name); //here we are using bindParam to bind the value to field with $name variable.$your_stmt->execute();// finally execute statement is used to execute all above stuff.
See also
No comments:
Post a Comment