To create a MySQL database using PHP, you can use the `mysqli` extension. Here's an example:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$databaseName = "your_database";
$sql = "CREATE DATABASE $databaseName";
if ($conn->query($sql) === true) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// Close the connection
$conn->close();
?>
In the code above, replace `your_username` and `your_password` with your actual MySQL credentials. The code creates a connection to the MySQL server. If the connection is successful, it creates a new database using the `CREATE DATABASE` SQL statement.
You need to replace `your_database` with the desired name for your database. After executing the `CREATE DATABASE` query, it checks if the operation was successful and displays an appropriate message.
Remember to handle errors properly in your code. The example above shows a basic error handling approach by using `die()` to terminate the script and display an error message if the connection fails or the database creation fails. In a production environment, you may want to handle errors more gracefully and log them instead of displaying them directly to users.
0 Comments: