I read on PDO and I searched on StackOverFlow about pdo and prepare statement. I want to know what are/is the benefits or using the prepare statement. eg:
$sql = 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
vs
$sql = "SELECT name, colour, calories FROM fruit WHERE calories < $calories AND colour = $colour";
$result = $connection->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
both queries will return the same result so why using the prepare, for me it looks like it's gonna be slower since you have to execute an extra step.
thanks
PDO::prepare — Prepares a statement for execution and returns a statement object.
SELECT query without parameters If there are no variables going to be used in the query, we can use a conventional query() method instead of prepare and execute. $stmt = $pdo->query("SELECT * FROM users"); This will give us an $stmt object that can be used to fetch the actual rows.
PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.
Prepared statements are:
Of these two, #1 is far more important and makes prepared statements indispensable! If you didn't use prepared statements, the only sane thing would be to re-implement this feature in software. (As I've done several times when I was forced to use the mysql
driver and couldn't use PDO
.)
Prepare is faster when using a lot of queries (you already prepared the query) and it's more secure.
Your second code probably won't work - you're using parameters in a query but you're not defining them.
With query() you have to fill the query manually using quote() - this is more work and tends to make programmers careless.
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