Languages
[Edit]
EN

PHP - how to make MySQL delete query with PDO?

5 points
Created by:
Kate_C
2860

In PHP it is possible to make SQL DELETE query with PDO in following way.

1. DELETE query with PDO example

<?php

	if(isset($_GET['name']))
	{
		$name = $_GET['name'];

		$db_name = 'test';
		$db_host = '127.0.0.1'; // 'localhost'
		$db_username = 'root';
		$db_password = 'root';

		$dsn = 'mysql:dbname=' . $db_name . ';host=' . $db_host . ';charset=utf8';
		$pdo = new PDO($dsn, $db_username, $db_password);
		
		$statement = $pdo->prepare('DELETE FROM `users` WHERE `name` = :name');

		if($statement === FALSE)
			die('Query preparation error!');

		$parameters = array(
			'name' => $name
		);

		if($statement->execute($parameters))
		{
			$count = $statement->rowCount();
			
			echo 'Number of deleted rows is ' . $count . '.';
		}
		else
			echo 'Query execution error!';
	}

?>

Running:

http://localhost/delete-user.php?name=John

Result:

SQL DELETE query with PDO class - PHP / MySQL.
SQL DELETE query with PDO class - PHP / MySQL.

Database:

Database state after SQL DELETE query with PDO class - PHP / MySQL.
Database state after SQL DELETE query with PDO class - HeidiSQL

2. Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`role` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

insert_data.sql file:

INSERT INTO `users`
	(`name`, `role`)
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

See also

  1. PHP - how to prevent SQL injection?
  2. PHP - how to make MySQL insert query with PDO?
  3. PHP - how to make MySQL select query with PDO?
  4. PHP - how to make MySQL update query with PDO?
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.