Why do I have to assign the value of the prepare method to a variable to only after instantiating the execute? I can not

4

Ex:

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

Why does not it work if I instantiate the execute method of the same instance? since the value has already been passed to the prepare method? ex:

$db->prepare("SELECT * FROM DB");
$db->execute();
    
asked by anonymous 03.05.2014 / 16:00

2 answers

4

The% w_that is your PDO class has the prepare , which is responsible for preparing an execution command (SQL ) and that it returns a PDOStatement a> and it has execute method, that is, $db does not have this $db method, but has a method that returns a PDOStatement that has the execute.

In execute you can directly use the PDO :: query , which also returns a PDOStatement already run being the one with data return and PDO::exec , which executes Insert, Update, and Delete commands that return the number of affected rows.

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

Why does this all happen?

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

    
03.05.2014 / 17:18
2

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

Just think a little: $db can not 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 who you run .

Still the class PDO has a function PDO::exec which allows you to perform queries quickly, but without the possibility to search results, returning only the number of modified lines .

    
03.05.2014 / 17:17