Call to undefined method PDO::execute()

This is a common error to witness if you are a PHP developer who is learning how to use the PDO extension. The error in question reads as follows:

Fatal error: Call to undefined method PDO::execute()

Essentially, this fatal error is telling you that the PDO object does not have a method called execute.

Typically, when we use PDO to query MySQL, there are two objects being used:

  1. The PDO object.
  2. The PDOStatement object.

The above error usually occurs when you get those two objects mixed up. In this case, you are calling execute on the PDO object when you should be calling it on the PDOStatement object.

A typical PDO prepared statement gets executed like so:

  1. You prepare a statement using the PDO object.
  2. The PDO object returns a PDOStatement object. This object represents the statement that you prepared.
  3. You execute the prepared statement.

Take a look at the following example:

//Example SQL query.
$sql = "SELECT * FROM cities";

//Prepare the SQL statement.
$stmt = $pdo->prepare($sql);

//Execute the statement.

In the PHP above, we prepared the statement using PDO::prepare. This method returned a PDOStatement object, which I assigned to the variable $stmt. Finally, I executed the prepared statement by calling the PDOStatement::execute function.

Simply put: In your case, you are probably attempting to call execute on $pdo instead of $stmt.

Hopefully, this post helped to solve your issue!