Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a database using PDO in PHP?

Tags:

php

mysql

pdo

I want to create a class which uses PDO to interact with MySQL. Can I create a new MySQL table using PDO?

like image 985
Xerri Avatar asked Apr 06 '10 09:04

Xerri


People also ask

Can you create a database with PHP?

PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.

How does PDO connect to database?

A PDO database connection requires you to create a new PDO object with a Data Source Name (DSN), Username, and Password. The DSN defines the type of database, the name of the database, and any other information related to the database if required. These are the variables and values we stated inside the dbconfig.

What is PDO database?

PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way to access databases. This means developers can write portable code much easier. PDO is not an abstraction layer like PearDB. PDO is a more like a data access layer which uses a unified API (Application Programming Interface).


1 Answers

Yes, you can.

The dsn part, which is the first parameter of the PDO constructor, does not have to have a database name. You can simply use mysql:host=localhost. Then, given you have the right privilege, you can use regular SQL commands to create a database and users, etc.

Following is an example from an install.php file. It logs in with root, create a database, a user, and grant the user all privilege to the new created database:

<?php      $host = "localhost";      $root = "root";     $root_password = "rootpass";      $user = 'newuser';     $pass = 'newpass';     $db = "newdb";      try {         $dbh = new PDO("mysql:host=$host", $root, $root_password);          $dbh->exec("CREATE DATABASE `$db`;                 CREATE USER '$user'@'localhost' IDENTIFIED BY '$pass';                 GRANT ALL ON `$db`.* TO '$user'@'localhost';                 FLUSH PRIVILEGES;")         or die(print_r($dbh->errorInfo(), true));      }     catch (PDOException $e) {         die("DB ERROR: " . $e->getMessage());     } ?> 
like image 158
Jingshao Chen Avatar answered Sep 30 '22 01:09

Jingshao Chen