Welcome back to CodeYourCraft! Today, we're going to learn how to delete data from a database using PHP and MySQLi. This lesson is perfect for both beginners and intermediates. Let's dive in! π
Before we start, let's quickly recap the basics:
We'll be using MySQLi to interact with a MySQL database and delete records from a table.
First, let's create a simple database and table for this tutorial.
CREATE DATABASE if not exists my_database;
USE my_database;
CREATE TABLE if not exists users (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);Now, let's move on to PHP.
To connect to our database, we'll use the mysqli_connect() function.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>Replace username and password with your actual database credentials.
Now that we're connected to the database, let's delete a user by ID.
<?php
$sql = "DELETE FROM users WHERE id = 1";
if (mysqli_query($conn, $sql)) {
echo "User deleted successfully";
} else {
echo "Error deleting user: " . mysqli_error($conn);
}
?>This script will delete the user with ID 1.
π‘ Pro Tip: Always use prepared statements for better security when dealing with user input.
Deleting a single row is straightforward, but what about multiple rows?
<?php
$sql = "DELETE FROM users WHERE id IN (1, 2, 3)";
if (mysqli_query($conn, $sql)) {
echo "Users deleted successfully";
} else {
echo "Error deleting users: " . mysqli_error($conn);
}
?>This script will delete the users with IDs 1, 2, and 3.
What function do we use to delete a user from the database in PHP MySQLi?
That's it for today! You've learned how to delete data from a database using PHP MySQLi. Remember to always test your code and use prepared statements for better security.
In the next lesson, we'll explore how to update data in a MySQL database using PHP MySQLi. Stay tuned! π
Happy coding! π‘