PHP Create a MySQL Database
One or more tables comprise a database.
To establish or destroy a MySQL database you require special CREATE capabilities.
Create MySql Database
You must have basic knowledge of SQL query to create a mysql database.
The following queries are used to create a database in mysql:
CREATE DATABASE database_name
The following queries are used to delete a database in mysql:
DROP DATABASE database_name
Related Links
Create a MySQL Database Using MySQLi and PDO
The CREATE DATABASE command is used for building a MySQL database.
The examples below will establish a database called "myDB" :
Example (MySQLi Object-oriented)
The query()
method from mysqli
class is used to execute a SQL
statement or query.
The query()
gets two arguments which is a connection object and a string should contain a sql query.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// Close connection
$conn->close();
?>
Example (MySQLi Procedural)
The mysqli_query()
method used to execute a SQL statement or query.
The mysqli_query()
gets two arguments which is a connection object and a string should contain a sql query.
Example (PDO)
The exec()
method from PDO
class is used to execute a SQL statement
and it does not return any results from database.
The exec()
takes an argument which is a sql query as string.
exec($sql);
echo "Database created successfully
";
} catch(PDOException $e) {
echo $sql . "
" . $e->getMessage();
}
// Close connection
$conn = null;
?>
Tip :- PDO has a wonderful advantage in that it contains an exception class to handle any difficulties that may arise in our database queries.
Related Links