Why do I have to assign the value of the prepare method to a variable and only then instantiate execute? in Pdo

Asked

Viewed 156 times

4

Ex:

$stmt = $db->prepare("SELECT * FROM BD");
$stmt->execute();

Why doesn’t it work if I instantiate the execute method from the same instance? since the value has already been passed to the prepare method? eg:

$db->prepare("SELECT * FROM DB");
$db->execute();

2 answers

4


The $db which is your class variable PDO has the method prepare, who is responsible for preparing an execution command (SQL) and that the same returns a Pdostatement and in it has the method execute, ie, $db does not have this method execute but, it has a method that returns a Pdostatement who has the run.

In the $db you can directly use the PDO::query, that also return a Pdostatement already executed being the one with data return and PDO::exec, which executes Insert, Update and Delete commands that return the amount of affected lines.

//select
$db->query("SELECT * FROM BD");

//insert, update e delete
$rowsafetados = $db->exec("INSERT INTO BD ...");

'Cause this is all happening?

There is separation of responsibility between classes (POO) and each class has its own responsibility, $db connection and fast methods, and Pdostatement using the $db as a connection to your methods.

  • optionally it can chain calls $result = $db->prepare("SELECT * FROM BD")->execute();

  • will even work, but, the problem that ai will not be returned a Pdostatement, it will return a bool as described on the PHP.net website (http://www.php.net/manual/en/pdostatement.execute.php), maybe for some cases it works well but it is best to use a Pdostatement

  • you’re right, it should be fetch or fetchAll.

2

Because $db is an instance of the class PDO and it represents a connection with the database. Already $stmt in turn is an instance of the class PDOStatement, which in simple terms represents a single query.

Just think about it: $db can’t be executed because it is a connection, running a connection would be the act of connecting, but you are already connected. So $stmt represents a query, and it’s her you executes.

Still the class PDO has a function PDO::exec that allows you to perform queries quickly, but without the possibility to search for results, having as return only the amount of modified lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.