PHP MySQL Database
In the previous tutorial, we create
PHP Connection To MySQL. For this follow-up tutorial, I decided to make a tutorial on
How To Create MySQL Database. For creating a database, it will consist one or more tables in one database. We create a database and name it as
“myDatabase”.
Creating MySQL Database Using MySQLi and PDO
Example database name "myDatabase".
Example MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection Error. Check your syntax." . $conn->connect_error); }
// Create database
$sql = "CREATE DATABASE myDatabase";
if ($conn->query($sql) === TRUE) {
echo "Successfully Created The Database";
} else {
echo "Error creating database. Check the Syntax." . $conn->error;
}
$conn->close();
?>
Example database name "myDatabase".
Example MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
// Check connection
if (!$conn) {
}
// Create database
$sql = "CREATE DATABASE myDatabase";
echo "Successfully Created The Database";
} else {
echo "Error creating database. Check the Syntax." . mysqli_error($conn); }
?>
Example database name "myDatabase".
Example PDO (PHP Data Objects)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDatabase";
// use exec() because no results are returned
echo "Successfully Created The Database<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I use PHPMyAdmin to create a database in MySQL. After creating my database in PHPMyAdmin, this is my query using PDO in shortcodes.
<?php
$conn = new PDO("mysql:host=localhost;dbname=myDatabase", 'username', 'password');
?>
Share us your thoughts and comments below. Thank you so much for dropping by and reading this tutorial post. For more updates, don’t hesitate and feel free to visit this website more often and please share this with your friends or email me at
[email protected]. Practice Coding. Thank you very much.