Search code examples
phpdatabasepdosql-delete

How to delete a row in a database with pdo ($stmt stated false)


I'm coding a blog to get experience with php.

I want the admin to be able to delete a post, but when I click the delete-button which should actually bring me to a function that deletes the post I get the error Call to a member function execute() on boolean.

Here is the code of the postsRepository.php which interacts with the database and the function in the postsAdminController.php:

public function deletePost($id)
{
  $table = $this->getTableName();
  $model = $this->getModelName();

  $stmt = $this->pdo->prepare("DELETE * FROM `{$table}` WHERE id = :id");

  $stmt->execute([
   'id' => $id
  ]);
 }


public function deletePost()
{
  $id = $_GET['id'];

  if ($this->postsRepository->deletePost($id)) {
    header("Location: posts-admin");
    return;
  } else {

  }
}

I've var_dumped the $id right before the $stmt, it's correct and the shown error says the it is because of $stmt->execute([.

The $stmt is stated as false when I var_dumped it, but why?


Solution

  • The correct syntax for DELETE is

    DELETE FROM tableName WHERE ...
    

    Remove the * in your query.

    $stmt is false because "If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling)."

    For more informations, check the documentation