Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO's query vs execute

Tags:

php

pdo

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(); 

?

like image 893
Qiao Avatar asked Jan 15 '11 16:01

Qiao


People also ask

What is the difference between PDO query () vs execute ()?

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?

What is execute in PDO?

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().

Which function is used to execute the query in PDO?

To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method.

Which PDO method is used to prepare a statement for execution?

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.


1 Answers

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?

like image 145
Gilean Avatar answered Oct 08 '22 12:10

Gilean