Is the cost of using prepare and query the same for the same SQL query statement?
$sql = $pdo -> prepare("select * from table");
$sql -> execute();
$rs = $sql -> fetch(PDO :: FETCH_ASSOC );
$sql = $pdo -> query("select * from table");
$rs = $go -> fetch(PDO::FETCH_ASSOC);
For example, if the above prepare and query queries The efficiency is the same? (Ignore SQL statement injection).
Single itemWhich one is better for query results?
Will prepare send the database at least twice to the database when querying?
Is PDO prepare only suitable for select? What about the other two operations update and insert into? Using placeholders in prepare can effectively prevent injection, but when? ="abc./- #$%`123" These special symbols (unless they are escaped), an error is reported when executing the statement. Is
exec more suitable for update and insert into?
阿神2017-06-05 11:09:31
1.PDO::query executes a SQL statement and, if passed, returns a PDOStatement object. The PDO::query function has a "very good thing", that is, it can directly traverse the returned record set.
2.PDO::exec executes a SQL statement and returns the number of affected rows. This function does not return a result collection. Official recommendation:
For SELECT statements that only need to be issued once in the program, consider using PDO::query().
For statements that need to be issued multiple times, you can use PDO::prepare() to prepare a PDOStatement object and use PDOStatement::execute() to issue the statement.
PDO::exec supports the execution of all SQL statements such as SELECT/DELETE/UPDATE/INSERT, so it is much more powerful than the PDO query() function. Since only the affected functions are returned, if you execute SELECT, you cannot get the PDOStatement object, so you cannot traverse the result set. You can only use the query or execute function according to official recommendations. .
3. The principle of prepare is this. The sql statement is sent to the sql server for compilation in advance, and then it is actually executed when exec is executed. Compile once, execute many times. If there is only one query, the efficiency of prepare and query are basically the same. If executed multiple times, the efficiency of prepare will be revealed. In addition, not all SQL injections can be prevented, such as where in (" ").