Sling Academy
Home/PHP/PHP & MySQL: How to create/alter/drop tables

PHP & MySQL: How to create/alter/drop tables

Last updated: January 12, 2024

Overview

In today’s web development scenario, managing databases is a crucial skill. MySQL is one of the most popular relational database management systems, and PHP is a server-side scripting language that is widely used for web development. Often, these two are combined to manage the backend data of a web application effectively. In this tutorial, we will go through the essential operations of creating, altering, and dropping tables in a MySQL database using PHP.

What Will You Learn?

  • How to set up a PHP script to connect to MySQL
  • Creating MySQL tables utilizing PHP
  • Altering tables to fit evolving data requirements
  • Dropping tables that are no longer necessary
  • Best Practices in PHP and MySQL

Prerequisites

Before we start, make sure you have a PHP environment setup, access to a MySQL database, and a basic understanding of SQL and PHP.

Setting Up a Database Connection

Our first step is to establish a connection with the MySQL database:

<?php
$servername = 'localhost';
$username = 'your_username';
$password = 'your_password';
$dbname = 'your_dbname';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';
?>

Creating Tables

Once connected, we can start creating tables. Here’s a simple example:

<?php
$sql = "CREATE TABLE users (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  firstname VARCHAR(30) NOT NULL,
  lastname VARCHAR(30) NOT NULL,
  email VARCHAR(50),
  reg_date TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
  echo "Table users created successfully";
} else {
  echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

This script will create a table named ‘users’ with columns for user ID, first name, last name, email address, and registration date.

Altering Tables

To change the structure of an existing table:

<?php
$sql = "ALTER TABLE users
ADD birthday DATE NOT NULL";

if ($conn->query($sql) === TRUE) {
  echo "Table altered successfully";
} else {
  echo "Error altering table: " . $conn->error;
}

$conn->close();
?>

This will add a new column ‘birthday’ of type DATE to the ‘users’ table.

Dropping Tables

If you want to remove a table completely, use the DROP TABLE command:

<?php
$sql = "DROP TABLE if exists users";

if ($conn->query($sql) === TRUE) {
  echo "Table dropped successfully";
} else {
  echo "Error dropping table: " . $conn->error;
}

$conn->close();
?>

Best Practices

  • Regularly back up your database before performing operations that alter its structure.
  • Ensure to sanitize and validate user input to safeguard against SQL injection.
  • Use mysqli_real_escape_string() or prepared statements for better security.
  • Close your database connections to free up resources.

Conclusion

Creating, altering, and dropping tables are fundamental operations that you’ll perform while managing a MySQL database with PHP. With the knowledge you’ve gained from this tutorial, these tasks should become routine components of your web development work.

Next Article: PHP & MySQL: How to Auto Backup Database (6 Steps)

Previous Article: A few ways to host a PHP site for free

Series: Building Dynamic Web Pages with PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array