I want to create a class which uses PDO to interact with MySQL. Can I create a new MySQL table using PDO?
PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
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.
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).
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()); } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With