📜  PHP mysql-create Table(1)

📅  最后修改于: 2023-12-03 15:18:20.489000             🧑  作者: Mango

PHP MySQL - Create Table

In this tutorial, we will learn how to create a table in MySQL database using PHP. We will cover the following topics:

  1. Connecting to MySQL database using PHP
  2. Creating a table in MySQL database using PHP
  3. Dropping a table in MySQL database using PHP
Connecting to MySQL database using PHP

First of all, we need to connect to a MySQL database using PHP. We can do this by using mysqli_connect() function in PHP.

// MySQL database credentials
$host = "localhost";
$username = "root";
$password = "password";
$dbname = "test_db";

// Connect to MySQL database
$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Creating a table in MySQL database using PHP

Once we have connected to the MySQL database, we can create a table using mysqli_query() function in PHP. We need to pass the SQL query as an argument to this function.

// Create a table in MySQL database
$sql = "CREATE TABLE employees (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(30) NOT NULL,
    last_name VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    gender ENUM('male','female') NOT NULL,
    date_of_birth DATE,
    hire_date DATE
)";

if (mysqli_query($conn, $sql)) {
    echo "Table employees created successfully";
} else {
    echo "Error creating table: " . mysqli_error($conn);
}

In the above code, we are creating a table named employees with columns id, first_name, last_name, email, gender, date_of_birth, and hire_date.

Dropping a table in MySQL database using PHP

If we want to delete a table from MySQL database, we can use DROP TABLE statement in SQL. We can execute this statement using mysqli_query() function in PHP.

// Drop a table in MySQL database
$sql = "DROP TABLE employees";

if (mysqli_query($conn, $sql)) {
    echo "Table employees droped successfully";
} else {
    echo "Error dropping table: " . mysqli_error($conn);
}

In the above code, we are dropping the employees table from MySQL database.

Conclusion

In this tutorial, we have learned how to create and drop a table in MySQL database using PHP. We have covered the basics of connecting to a MySQL database using PHP, creating a table with columns, and dropping a table from MySQL database.