Home >Database >Mysql Tutorial >Can I Create a Database Using PDO in PHP?

Can I Create a Database Using PDO in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 16:24:02667browse

Can I Create a Database Using PDO in PHP?

Creating a Database with PHP's PDO

In PHP development, the PDO (PHP Data Objects) extension provides a consistent interface for interacting with various database systems, including MySQL. One common task is the creation of a new database using PDO.

Can you create a database with PDO?

Yes, you can create a database using PDO in PHP.

How To Create a Database Using PDO

To create a database using PDO, you can use the PDO::exec() function. This function allows you to execute SQL queries and statements directly on the database server. Here's an example of creating a database called "my_database":

$dsn = 'mysql:host=localhost;dbname=mysql';
$username = 'root';
$password = 'mypassword';

try {
    $db = new PDO($dsn, $username, $password);
    $db->exec("CREATE DATABASE my_database");
    echo "Database created successfully";
} catch (PDOException $e) {
    echo "Error creating database: " . $e->getMessage();
}

Note: Make sure you have the necessary permissions to create the database on the database server.

The above is the detailed content of Can I Create a Database Using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn