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:
- The PDO object.
- 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:
- You prepare a statement using the PDO object.
- The PDO object returns a PDOStatement object. This object represents the statement that you prepared.
- 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. $stmt->execute();
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!