PHP MySQL: Delete Data
Deleting data in MySQL using PHP involves executing an SQL DELETE
statement. This allows you to remove one or more rows from a specified table based on a condition.
Steps to Delete Data
- Connect to the MySQL Database
- Write the SQL
DELETE
Query - Execute the Query
- Check for Success
- Close the Connection
Syntax for SQL DELETE
table_name
: The name of the table where data will be deleted.condition
: Specifies which rows to delete. Always include aWHERE
clause to avoid deleting all rows.
Code Example: Delete Data
1. Establish a Database Connection
2. Execute an SQL DELETE
Query
Delete a user based on their ID:
Using Prepared Statements for Security
Prepared statements are recommended to avoid SQL injection, especially for dynamic inputs.
Delete Multiple Records
You can delete multiple rows that match specific conditions:
Delete All Rows
To delete all rows in a table without removing the table itself, omit the WHERE
clause:
Warning: Without a
WHERE
clause, all rows in the table will be deleted. Use with caution.
Complete Example
Key Notes
- Always Use WHERE: Avoid accidental deletion of all rows by including a specific
WHERE
clause. - Use Prepared Statements: Protect against SQL injection when working with dynamic inputs.
- Backup Data: Always back up your database before running delete queries.
- Check Affected Rows: Use
$conn->affected_rows
or$stmt->affected_rows
to verify the number of rows deleted.
Check Number of Affected Rows
Let me know if you need more advanced examples or help with error handling!