How can PHP be used to create a MySQL database and user?

To create a MySQL database and user using PHP, you can use the mysqli extension to connect to MySQL and execute SQL queries. First, you need to connect to MySQL using a valid username and password with the necessary privileges to create databases and users. Then, you can use SQL queries to create a new database and user with the desired permissions.

<?php

$servername = "localhost";
$username = "root";
$password = "password";

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE mydatabase";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

// Create user
$sql = "CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'";
if ($conn->query($sql) === TRUE) {
    echo "User created successfully";
} else {
    echo "Error creating user: " . $conn->error;
}

$conn->close();

?>