Are they both do the same thing, only differently?
Is there any difference besides using prepare
between
$sth = $db->query("SELECT * FROM table"); $result = $sth->fetchAll();
and
$sth = $db->prepare("SELECT * FROM table"); $sth->execute(); $result = $sth->fetchAll();
?
query runs a standard SQL statement without parameterized data. Best practice is to stick with prepared statements and execute for increased security. See also: Are PDO prepared statements sufficient to prevent SQL injection?
PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement. PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query().
To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method.
Description ¶ Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'); $sth->bindParam(':calories', $calories); $sth->bindParam(':colour', $colour); $sth->execute(); // $calories or $color do not need to be escaped or quoted since the // data is separated from the query
Best practice is to stick with prepared statements and execute
for increased security.
See also: Are PDO prepared statements sufficient to prevent SQL injection?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With