PHP MySQLi Delete Data 🎯

beginner
15 min

PHP MySQLi Delete Data 🎯

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! πŸ“

Introduction πŸ“

Before we start, let's quickly recap the basics:

  • PHP is a popular server-side scripting language.
  • MySQLi is a MySQL interface extension for PHP.

We'll be using MySQLi to interact with a MySQL database and delete records from a table.

Setting Up the Database πŸ“

First, let's create a simple database and table for this tutorial.

sql
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.

Connecting to the Database πŸ“

To connect to our database, we'll use the mysqli_connect() function.

php
<?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.

Deleting Data πŸ“

Now that we're connected to the database, let's delete a user by ID.

php
<?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 Multiple Rows πŸ“

Deleting a single row is straightforward, but what about multiple rows?

php
<?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.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What function do we use to delete a user from the database in PHP MySQLi?

Conclusion πŸ“

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! πŸ’‘