![](https://maz.kr/wp-content/uploads/2022/07/php-mysql-delete-thumbnail.png)
MySQL 데이터 삭제
DELETE 문은 테이블에서 레코드를 삭제하는 데 사용된다.
DELETE FROM table_name WHERE some_column = some_value
DELETE 구문 의 WHERE 절에 주의해야한다.
WHERE 절은 삭제할 레코드를 지정한다.
WHERE 절을 생략하면 모든 레코드가 삭제되니 반드시 주의 하자.
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Moe | mary@example.com | 2014-10-23 10:22:30 |
3 | Julie | Dooley | julie@example.com | 2014-10-26 10:48:23 |
“MyGuests” 테이블에서 id=3인 레코드를 삭제해보자.
MySQLi 객체 지향
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "DELETE FROM MyGuests WHERE id=3"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } $conn->close();
MySQLi 절차
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } mysqli_close($conn); ?>
PDO
PHP
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "DELETE FROM MyGuests WHERE id=3"; $conn->exec($sql); echo "Record deleted successfully"; } catch(PDOException $e) { echo $sql . "
" . $e->getMessage(); } $conn = null; ?>
레코드가 삭제되면 테이블은 다음과 같이 표시된다.
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Moe | mary@example.com | 2014-10-23 10:22:30 |
참고
W3C School - PHP MySQL Delete Data
W3C School - SQL Tutorial
W3C School - PHP Tryit Editor