简体   繁体   中英

PHP PDO can't delete record

I'm having a bit of a problem with PDO deleting a record from the database.

It just returns false, and I can't seem to see why, can anyone help? The code:

$db = new PDO('sqlsrv:Server='.DB_HOST.';Database='.DB_NAME, DB_USER, DB_PASS);
$query = $db->prepare('DELETE * FROM '.$table.' WHERE id = :id');
$query->bindValue(':id', $id);
$query->execute();

I've also tried:

$db = new PDO('sqlsrv:Server='.DB_HOST.';Database='.DB_NAME, DB_USER, DB_PASS);
$db->exec('DELETE * FROM '.$table.' WHERE id = '.$id);

And I know the user from the DB has permissions to delete because I can run the query with success in the SQL client.

Any ideas?

Thanks :)

DELETE FROM $table WHERE id = $id
  • there is no * in the DELETE statement

Go here for some easy documentation .

Your first example is fine, bar one error

$db = new PDO('sqlsrv:Server='.DB_HOST.';Database='.DB_NAME, DB_USER, DB_PASS);
$query = $db->prepare('DELETE FROM '.$table.' WHERE id = :id');
$query->bindValue(':id', $id);
$query->execute();

You don't need a * in a simple delete statement.

FYI, rowCount() will work well for confirming the delete worked, as follows:

$countDel = $query->rowCount();
if ($countDel == 0) {
echo "No rows deleted";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM