Databases 4 min read

Creating a MySQL Database on Linux Using PHP (mysqli)

This tutorial explains how to create a MySQL database on a Linux system using PHP's mysqli extension, covering prerequisite installations, establishing a connection to the MySQL server, and executing SQL statements to create the database, with complete code examples and instructions for customizing credentials.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Creating a MySQL Database on Linux Using PHP (mysqli)

MySQL is a widely used relational database management system that runs on various operating systems, including Linux. In a Linux environment you can use a PHP script to create a MySQL database. This article introduces how to write such a script and provides concrete code examples.

Before you begin, ensure that PHP, MySQL, and the PHP MySQL extension are installed on your Linux system.

First, you need to use PHP's MySQL extension to connect to the MySQL server. Both mysqli and PDO can be used; this guide uses the mysqli extension.

Example code: connecting to the MySQL server

<code><?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";

// 创建连接
$conn = new mysqli($servername, $username, $password);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

echo "连接成功";

$conn->close();
?>
</code>

In the code above, replace your_username and your_password with your MySQL credentials.

Next, use a PHP script to create a database.

Example code: creating a database named my_database

<code><?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "my_database";

// 创建连接
$conn = new mysqli($servername, $username, $password);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 创建数据库
$sql = "CREATE DATABASE $dbname";
if ($conn->query($sql) === TRUE) {
    echo "数据库创建成功";
} else {
    echo "数据库创建失败: " . $conn->error;
}

$conn->close();
?>
</code>

Replace your_username , your_password , and my_database with your own values.

After running the script, a success message will be displayed if everything works, and you can verify the new database by accessing the MySQL server.

Creating a MySQL database via PHP on Linux involves two key steps: connecting to the MySQL server and executing a CREATE DATABASE statement. You can adapt the provided code to suit your specific requirements.

backendDatabaseMySQLmysqli
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.