PHP CHAPTER 31

MySQL Create DB

PHP can execute SQL to create a MySQL database.

📘

What is it?

PHP can execute SQL to create a MySQL database.

💡

Why do we use it?

This can be useful during initial application setup.

⚙️

How does it work?

PHP connects to the MySQL server without selecting a database and executes CREATE DATABASE.

🧩

Syntax

PHP Syntax
CREATE DATABASE IF NOT EXISTS database_name;
💻

Example

PHP Example
<?php

$conn = new mysqli("localhost", "root", "");

if ($conn->connect_error) {
    die("Connection failed");
}

$sql = "CREATE DATABASE IF NOT EXISTS aifa_php_lab";

if ($conn->query($sql)) {
    echo "Database Ready";
}

?>
🔍

Example Explained

The connection is made without a database because the database is being created. query executes the SQL.
🚀

More Examples

Use phpMyAdmin to create the database manually during development.

⚠️ Important Rules

The MySQL user must have permission to create databases.

❌ Common Mistakes

Trying to select the database before it exists.

🌍 Real-World Use

Installation and setup scripts.

📝 Practice Exercise

Create an automatic database setup page.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →