All Tutorials

Your One-Stop Destination for Learning and Growth

Creating an MySQL Database with PHP Script

In this blog post, we will discuss how to create an MySQL database using a PHP script. This method is useful when you want to automate the process of creating databases and tables for your web applications.

Prerequisites

Before proceeding, make sure that:

  1. You have installed MySQL Server on your local machine or server environment.
  2. You have created a new PHP file with a .php extension.

Setting Up the Connection

The first step is to establish a connection between our PHP script and MySQL server. We will use the mysqli_connect() function to do this.

<?php
$servername = "localhost"; // replace with your server name
$username = "root"; // replace with your MySQL username
$password = ""; // replace with your MySQL password
$dbname = "newdatabase"; // replace with the desired database name

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

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

Creating the Database

Unfortunately, PHP does not allow you to create a database using pure PHP code. Instead, you can use MySQL commands through your PHP script. For this example, we will create the database outside of the PHP script and focus on creating tables within it.

Creating Tables

To create tables in our newly created database, we will use SQL statements and execute them using PHP functions. Here's an example:

<?php
// Create table query
$sql = "CREATE TABLE users (
 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 username VARCHAR(30) NOT NULL,
 email VARCHAR(50) NOT NULL,
 password VARCHAR(255) NOT NULL,
 registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 INDEX user_id (id)
)";

// Execute query
if (mysqli_query($conn, $sql)) {
 echo "Table 'users' created successfully.";
} else {
 echo "Error creating table: " . mysqli_error($conn);
}
?>

Replace the $sql variable with your desired table structure and SQL syntax. This example creates a table named users with columns for username, email, password, and a timestamp field named registration_date.

Wrapping Up

In this blog post, we've covered how to create an MySQL database using a PHP script. Remember that creating the database itself cannot be done through PHP; you need to use MySQL commands or tools outside of your PHP code. Instead, we focused on creating tables within the existing database. This method is useful when automating the process of setting up databases for your web applications.

Now, go ahead and experiment with different table structures and SQL queries. Happy coding!

Published November, 2015