What is the correct syntax for creating a MySQL database using PHP?
To create a MySQL database using PHP, you need to establish a connection to the MySQL server and then execute a SQL query to create the database. The MySQLi extension is commonly used in PHP for interacting with MySQL databases. You can use the mysqli_connect() function to connect to the MySQL server and mysqli_query() function to execute the SQL query to create the database.
<?php
// Database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE $dbname";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Keywords
Related Questions
- How can the syntax for WHERE...IN be correctly implemented with bind_param in PHP to avoid errors in the query?
- How can PHP developers ensure better readability and maintainability by separating HTML code from PHP logic?
- Are there any common pitfalls when parsing the $_SERVER['HTTP_USER_AGENT'] string in PHP?