PHP how to make a database

Learn how to create a database in PHP with an example. Create tables, structure data and store information with ease!

Creating a Database in PHP

Creating a database in PHP is a relatively easy process. The first step is to create a connection to your database server. The following example shows how to create a connection to a MySQL server.


$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

Once you have established a connection, you can create a database. To do this, we need to use a simple SQL query as follows.


$sql = "CREATE DATABASE myDB";

if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

Now that the database has been created, we can create tables inside the database. To do this, we need to use another SQL query as follows.


$sql = "CREATE TABLE MyGuests (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
    )";

if ($conn->query($sql) === TRUE) {
    echo "Table MyGuests created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

The above example creates a table named "MyGuests" with a few columns. You can modify the example to add more columns and data types as needed. Once the table has been created, you can use SQL queries to insert, update, and delete data from the table.

Creating a database in PHP is a straightforward process. Once the connection has been established and the database and tables have been created, you can start working with the data. You can use the same SQL queries to perform various operations such as inserting, updating, and deleting data.

Answers (0)